vue中各种通信传值方式总结(2)

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { message: '我是阿格斯之盾' }, mutations: { MESSAGE_INFO (state,view) { state.message = view; } } }) export default store

(2)在min.js中注册store仓库 代码如下:

import Vue from 'vue' import App from './App' import router from './router' import store from './store' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })

(3)状态的读取和提交 还是使用上面的案例,我们以子组件About提交改变状态,父组件Head接受状态并显示出来下面是About组件提交状态

<template> <div> <button @click="handleChange">点击发送消息给父组件</button> </div> </template> <script> export default { name: 'About', props:{ 'text':[] }, data () { return { message: "" } }, mounted(){ }, updated(){ }, methods:{ handleChange(){ this.$store.commit("MESSAGE_INFO" , "我是火车王") //提交改变状态 } } } </script> <style scoped> </style>

Head组件接受状态:

<template> <div> <About></About> <p>来自子组件的消息:{{this.$store.state.message}}</p> //直接使用this.$store.state.message接受数据显示 </div> </template> <script> import About from '@/components/About.vue' export default { name: 'Head', components:{ About }, data () { return { message : "" } }, mounted(){ }, methods:{ } } </script> <style scoped> </style>

总结:以上就是vue中的通信方式,当然还有一些,比如说eventBus什么的,适用于中小型项目,但是我用的比较少,一般上面的几种在开发中已经够用的,例子很简单,学习是永无止境的,具体更深的东西还得下功夫去研读官网或者其他资料,本文中有不对的地方或者疑惑的地方,还望大家多多指教!谢谢。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/86c685a0c5f2f26cce9a8e187857c58c.html