开发

注册组件以及向组件传递值,通过props['aaaa'],声明属性,引用组件通过.

<chat :aaaa = "cartlist"></chat>


new Vue({

        el: '#app',
        components: {
            Chat
        },
        data() {
            return {
                cartList: []
            }
        },
      
        }
    })
 var Chat = {
        template: `<div>
     购物车
    <table border="1">
        <tr>
            <th>选中</th>
            <th>数量</th>
            <th>价格</th>
            <th>名称</th>
        </tr>
        <tr v-for ="(item,index) in aaaa">
            <td><input type="checkbox" v-model="item.select"> </td>
            <td><span @click="reducecount(index)"> - </span>{{item.count}}<span @click="addcount(index)"> + </span></td>
                <td>{{item.count * item.price}}</td>
                <td>{{item.text}}</td>
        </tr>


    </table>

</div>`
        , props: ['aaaa'],
        methods: {
            reducecount(val) {
                if (this.cartList[val].count > 1) {
                    this.cartList[val].count--;
                } else {
                    console.log(this.cartList[val].text)
                    if (window.confirm(`是否删除${this.cartList[val].text}?`)) {
                        this.cartList.splice(val, 1)
                    }
                }

            },
            addcount(val) {
                this.cartList[val].count++

            },
        }

    }
过滤掉一些数据
 chooseCount() {
                return this.aaaa.filter(v => v.select).length
            },

监听 computed

定义:
computed: {
            numString() {
                return Number(this.n1) + Number(this.n2) + Number(this.n3)
            }
        }
使用
        template: '<div> 简单的计算:<input type="text" v-model="n1">+<input type="text" v-model="n2">+<input type="text" v-model="n3">={{numString}}' +

深度监听

   watch:{
          aaaa:{
              handler(){
                  window.localStorage.setItem("chat",JSON.stringify(aaaa))
              },
              deep:true
          }  
        },

页面存储数据

   window.localStorage.setItem("chat",JSON.stringify(aaaa))

本地存储 json序列化和反序列化

                 window.localStorage.setItem("chat",JSON.stringify(this.a))
            this.cartList = JSON.parse(window.localStorage.getItem("chat"))

  • Vue-cli :脚手架
  • Vue-router:路由
  • Vuex:状态管理。
  • http :axios

项目的配置


image.png

启动项目cnpm run serve

阻止表单的提交

e.preventDefault()

重定向

router.js
  {
    path: '/',
    name: 'Regist',
    redirect: "/login",
  },

async, await异步调用

  async submitHandler(e){
                e.preventDefault()
                try{
                    const result = await  this.$http.get("/api/login",{params:this.model}))
                }catch (e) {
                    console.log(e)
                    
                }

Vuex

调用

                    this.$store.commit('setToken',result.data.token)

state: {
    tokens:''
  },
  mutations: {//同步的方法
    setToken(state,token){//setToken 方法名
      state.tokens = token
    }
  },
  actions: {
  },
  modules: {
  },
  getters:{

  }

本地存储window.localStorage.setItem("token",result.data.token)

axios全局请求拦截

  • 设置拦截器
import  axios from 'axios'
import  store from './store'
import  router from './router'

//http 全局拦截
//token 放在header的请求头上 传给后台。

export  default  function setAction() {

    //将token配置到header
    axios.interceptors.request.use(
        config  =>{
            if(store.state.tokens){
                config.headers.token = store.state.tokens
            }
            return config
        }
    )

    //每次的返回都会经过拦截器
    axios.interceptors.response.use(
         response =>{
             if(response.status == 200){
                 const data = response.data
                 if(data.code == -1){
                     //登陆过期了,清空localstorege和store中的记录清除
                     store.commit('token','')
                     window.localStorage.removeItem('token')
                     //跳转到login
                     router.replace({path:'/login'})

                 }
                 return data
             }
             return  response
         }
    )
}

main.js中执行方法

import setaxios from './setaxios'
setaxios()```


##### 嵌套路由的跳转
* 首先定义接收跳转的父容器

<template>
<div>
<router-view/>
</div>
</template>

  • 在父容器跳转路由中添加子路由
{
        path: '/bomnav',
        name: 'Bomnav',
        component: () => import(/* webpackChunkName: "about" */ '../views/Bomnav.vue'),
        children: [

            {
                path: 'index',
                name: 'index',
                component: () => import('../views/Index.vue')
            }, {
                path: 'classify',
                name: 'Classsify',
                component: () => import('../views/Classify.vue')
            }, {
                path: 'search',
                name: 'Search',
                component: () => import('../views/Search.vue')
            }, {
                path: 'car',
                name: "Car",
                component: () => import('../views/Car.vue')

            }, {
                path: 'mine',
                name: 'Mine',
                component: () => import('../views/Mine.vue')
            }

        ]
    }

  • 设置通过路由进行跳转到指定页面
    this.$router.push({path:'/bomnav/mine'})
给路由添加动画

https://www.cnblogs.com/szyblogs/p/7069577.html

子组件向父组件传递消息

子组件通过this.$emit('方法名')。父组件通过v-on:(方法名)接收

        子组件:template:`<div>{{title}}<button @click = "$emit('remove')">remove</button></div>`,
                 父组件:v-on:remove = "list.splice(index,1)"
父组件向子组件传递消息

子组件创建prop属性,父元素传递值

              子组件:props:['shuxing']
              父组件:v-bind: shuxing = "item.title"

props可以传递类型

props:{title:String}

字符串数组形式列出的 prop

props: ['title', 'likes', 'isPublished', 'commentIds', 'author']

props 可以直接传递,也可以通过v-bind动态赋值。
自定义v-model
    Vue.component('custom-input',{
                props:['checked'],
                model:{
                    prop:'checked',
                    event:'change'
                },
                template:
                    `<div>
                    <input type = "checkbox" v-bind:checked = "checked"  v-on:change = "$emit('change',$event.target.checked)">
                    </div>`
                
            })

    <div id="app7">
            <custom-input v-model="changeData"></custom-input>
            <p>{{changeData}}</p>
        </div>

复选框

<div id="app16">
            <input type="checkbox" id ="check" v-model = "checkboxs" value="jack"/>
            <label for = "jack">jack</label>
            
            
            <input type="checkbox" id ="check1" v-model = "checkboxs" value="lily"/>
            <label for = "lily">lily</label>
            
            <input type="checkbox" id ="check2" v-model = "checkboxs" value="sam" />
            <label for = "sam">sam</label>
            
            <p>选中的复选框{{checkboxs}}</p>
            
</div>
new Vue({
                el:"#app16",
                data:{
                    checkboxs:[]
                }
            })

vue插槽

    Vue.component("alert-box",{
                template:`<div class="demo-alert-box">
      <strong>Error!</strong>
      <slot></slot>
    </div>`
            })
            
            new Vue({
                el:'alert-box'
            })
<alert-box>something bad</alert-box>
font-family
span{
      font-family: PingFangSC-Medium; //mac电脑优先使用的字体。
}
光标变化cursor: pointer;
Vue.prototype是个Vue添加属性,而不是添加变量。
vue生命周期created中不能使用this,可以使用

`created(){
this.test()
// created:() =>{
// var that = this
// that.test()

                // console.log("created"+that.foo)
            },`
指令 解释
v-once 不改变界面 ,但是改变属性值
v-html 可以使用html
v-if 条件控制
v-bind :href = "url" 缩写:href ="url"
v-on:click ="dosomething" 缩写@click = "dosomething"
computed 计算属性,会使用相应式依赖使用缓存
method 会使用相应式依赖使用缓存
watch 监听属性
父组件向子组件传递 通过‘props’,子组件向父组件发送指令‘$emit[‘’]’
    
        Vue.component('custome_li',{
            template:`<li>{{title}} <button @click = "$emit('remove')">remove</button></li>`,
            props:['title']
        })
        new Vue({
            el:'#textli',
            data:{
                newText:" ",
                items:[{
                    id:1,
                    title:"11111"
                },{
                    id:2,
                    title:"22222"
                },{
                    id:3,
                    title:"33333"
                }]
            },
            methods:{
                addNewTod(){
                    
                }
            }
        })



<div id="textli">
            <form v-on:submit="addNewTod">
                <label> add new Text</label>
            <input v-model="newText" />
            <button>add</button>
            </form>
            
            <ul>
                <li is = "custome_li" v-for="item,index in items":key = "item.id" @remove = "items.pop(index,1)" :title = "item.title"></li>
            </ul>
            
        </div>
        

Vue中style的写法

:style="{ fontSize: fontSize + 'em' }"

:title 表示是动态传递数据, title中静态数据,类似:is也是动态数据,is是传递的静态数据。
    <div id = "example2">
        <custom_title title="test2222">
            
            </custom_title>
                
                
                <custom_title  :title = "test">
                    </custom_title>
                </div>


Vue.component('custom_title',{
                props:["title"],
                template:`<div>{{title}}</div>`,
            });
            
            new Vue({
                el:'#example2',
                data:{
                    test:"test1111"
                }
            });
后备插槽:
Vue.component('custom-btn',{
                template:`<button>
                    <slot>提交</slot>
                </button>`
            })

<div id="example10">
                    <custom-btn>
                    </custom-btn>
                    
                </div>
显示的内容是
<button>提交</button>。
如果
<div id="example10">
                    <custom-btn>
                                      注册
                    </custom-btn>
                    
                </div>
显示的内容是
<button>提交</button>。

v-slot:可以被替换为‘#’

slot 插槽作用域 对比

2.6.0之前的: 写法是 <template slot-scope= "slotprop">

<div id="app9">
            <base-layout-scope>
                <template slot-scope= "slotprop">
                    <div>{{slotprop.msg }}</div>
                </template>
            </base-layout-scope>            
        </div>

Vue.component('base-layout-scope',{
                template:`<div>
                    <slot :msg = "msg">{{person.teacher.name}}</slot>
                </div>`,
                data(){
                    return {
                        msg:'我是谁',
                        person:{
                            teacher:{
                                name:'韩梅梅',
                                age:20,
                                sex:'女'
                            }
                        }
                    }
                }
            })
        

2.6.0 之后的写法<base-layout-slot #item ="slotprop"或者<base-layout-slot v-slot:item ="slotprop"

    <div id="app10">
            <base-layout-slot #item ="slotprop"><div>{{
                slotprop.person.teacher.name
            }}</div></base-layout-slot>
            
        </div>


    Vue.component('base-layout-slot',{
                template:`<div>
                    <slot :item = "person"> {{person.teacher.name}}</slot>
                </div>`,
                data(){
                    return {
                        msg:'我是谁',
                        person:{
                            teacher:{
                                name:'韩梅梅',
                                age:20,
                                sex:'女'
                            }
                        }
                    }
                }
            })
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容