vue组件之间vuex传递数据

本文介绍了在vue项目开发中,组件之间如何使用Vuex进行数据传递。详细讲解了兄弟组件间通过store方式,父子组件间通过prop和$emit方式传递数据。同时,阐述了Vuex的安装、引入、状态映射到组件、状态修改以及官方推荐的修改方法。文章还提到了分模块管理状态仓库,并提供了相关参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue项目开发,组件之间传递数据

  1. 兄弟组件
    兄弟组件之间传输数据,用vuex的store方式。
  2. 父子组件
    父子组件之间传输数据,用vue的prop & $emit方式。

vuex:vue的状态管理工具

1.安装

npm install vuex --save

2.引入

./src/main.js

import Vue from 'vue'
import store from './store'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

./src/store/index.js

import Vue from 'vue'
import vuex from 'vuex'
import module1from '../static/js/module1.js'  //不同组件的变量建议分不同模块存放,方便管理

Vue.use(vuex)

export default new vuex.Store({
  state: {
    //  定义状态
    state1: {
      state1: '你好'  //可以是任何对象
    },
   ......
  },
  modules: {
    module1: module1,
   ......
  }
})

3.将状态映射到组件

xxx.vue

<template>
  <div>{{state1}}</div>
</template>
<script>
export default {
  computed : {
    state1() {
        return this.$store.state.state1.state1;
    },
  }
}
</script>

4.在组件中修改状态
通过点击按钮,触发setState方法,修改state1状态值,同时更新到页面中。

xxx.vue

<template>
<input v-model="inputText" placeholder="edit me">
<button @click="setState">按钮</button>
<p>{{state1}}</p>
</template>
<script>
export default {
  data() {
    return {
      inputText: ''
    };
  },
  computed: {
    state1() {
        return this.$store.state.state1.state1;
    },
  },
  methods: {
    setState: function () {
      this.$store.state.state1.state1 = this.inputText;
    },
  }
};
</script>

5.官方推荐的修改方法

./src/store/index.js

import Vue from 'vue'
import vuex from 'vuex'

Vue.use(vuex)

export default new vuex.Store({
  state: {
    //  定义状态
    state1: {
      state1: 'nihao'  //可以是任何对象
    },
  },
  mutations: {
    newState (state , msg) {
      state.state1.state1 = msg;
    }
  }
})

xxx.vue
只修改setState方法,其他全部不变。

<script>
	methods: {
	    setState: function () {
	      this.$store.commit('newState',this.inputText)
	    },
	}    
</script>

6.分模块管理状态仓库

./src/store/index.js

import Vue from 'vue'
import vuex from 'vuex'
import module1 from './module1.js'  
//不同组件的变量建议分不同模块存放,方便管理,建议存放在单独的文件夹中

Vue.use(vuex)

export default new vuex.Store({
  state: {
    state1: {
      state1: 'nihao'  //可以是任何对象
    },
  },
  mutations: {
    newState (state , msg) {
      state.state1.state1 = msg;
    }
  },
  modules: {
    moduleOne: module1,
  }
})

./src/store/module1.js

export default {
    state: {
      item:'testItem'
    }
}

xxx.vue

其他代码可以完全参照之前操作。

computed: {
    modelTest() {
        return this.$store.state.moduleOne.item;
    },
}

参考网站:
http://www.cnblogs.com/wisewrong/p/6344390.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值