vuex数据传递插件

vuex是数据传递插件,写入vuex中的数据为全局数据,不建议随意更改

 

导入vuex.js前需先导入vue.js
vuex可以在state中保存公共数据
在html中的使用方法{{this.$store.state.数据名}}
在vue实例中添加store:store(创建的vuex对象名)
写在vue实例之前

注意:
不推荐直接修改公共数据,把方法添加在vuex的mutations方法内,在创建组件的方法中使用this.$store(自定义).commit(“方法名”)调用vuex中的方法(方便维护)

创建vuex对象
const store=new Vuex.Store({
   //state相当于组件中的data,专门保存共享数据
   state:{
      //html调用{{this.$store.state.数据名}}
       name:“张三”
   },
  //储存公共方法
   mutations:{
      方法(state){
          console.log(state.name)
      }
   },
  getters:{
 html调用{{this.$store.getters.方法名}}
     方法名(state){
        return state.name
     }
   }
})

js组件
Vue.component(“grandfather”,{
     template:“#grandfather”,
    //把数据写在爷爷组件,父亲和儿子组件都可以用
     store:store,
     components:{
         “father”:{
               template:“#father”,
               components:{
            “son”:{
                template:“#son”,
                methods:{
                  方法(){
                     this.$store.commit(“公共方法”)
                   }
                }
            }
               }
          }
     }
})

在html中使用
<template id=“grandfather”>
    <div>
        //前面的参数固定改变name
        <p>{{this.$store.state.name}}</p>
    </div>
</>

posted @ 2021-03-24 16:44  终末s  阅读(40)  评论(0)    收藏  举报