vuex 子组件传值

以下是基础的使用方法,详细且深入使用方法详细见博客:https://segmentfault.com/a/1190000015782272

Vuex官网地址:https://vuex.vuejs.org/zh/guide/

 

步骤一:安装vuex 

 npm install vuex --save 

 

步骤二:简单使用

  • 构建核心仓库store.js

Vuex 应用的状态 state都应当存放在store.js 里面,Vue 组件可以从 store.js 里面获取状态,可以把 store 通俗的理解为一个全局变量的仓库。

但是和单纯的全局变量又有一些区别,主要体现在当 store 中的状态发生改变时,相应的 vue 组件也会得到高效更新

src 目录下创建一个 vuex 目录,vuex下创建 store.js 

 

  • store.js中
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);

export default new vuex.Store({
    // 首先声明一个状态 state
    state:{
        word:''
    },// 更新状态
    mutations:{
        changeWord(state, _word) {
            state.word = _word;
        }
    },
})

 

  • main.js中
import store from './vuex/store'

 

  • 传递

传递方法:

A界面改变store中state里的参数:  this.$store.commit( 'setId' ,(要传递的参数id) )

B界面接收变化数据参数: this.$store.state.id 

但是通过 vuex这样写,页面刷新之后,数据也会消失。它只是对变量提升。

 

A页面改变store中state的参数: 

methods:{
            sureChange () {
                this.$store.commit( 'changeWord' ,this.changeWord.trim());
                
                this.$router.push('/hbchange/2?id=2');
            }
        },

 

<button @click="changeword">按钮</button>

 

B页面

sureEdit () {
       console.log(this.$store.state.word )
}

 

posted @ 2019-01-04 12:05  Du.Du  阅读(323)  评论(0编辑  收藏  举报