The use of state management bus for Vue technology stack development and learning

Bus

1 Create a new component store.vue, register it in the routing list, and create a new component AInput.vue in the components directory (the components created by yourself are best to be prefixed)

{

path:'/store',

component:()=>import('@/views/store.vue')

}

components of AInput.vue

<template>

<input @input="handleInput" :value="value">//Bind input event and value value

</template>

<script>

export default{

name:'AInput',

props:{

value:{ // attribute value

type:[String,Number],

default:''

},

methods:{

handleInput(event){

const value = event.target.value//Get the input value of the text box

this.$emit('input',value)//pass the obtained value

//Pay attention to why you can't directly modify the value value here. This is the one-way data flow emphasized by vuex. Values ​​are passed between parent components. The modification of the value must be through the parent component. If the value is passed to the component and the child component, it must be passed Attribute, and the child component wants to modify the value passed by the parent component must be modified through the event

}

}

}

}

</script>

store.vue

<template>

<div>

//Use input component

<a-input v-model='inputValue' />//v-model two-way binding (equivalent to syntactic sugar, equivalent to: value="inputValue" @input="handleInput")

{{ inputValue }}//Display inputValue

</div>

</template>

<script>

import AInput from '_c/AInput.vue' //引入组件

export default{

name:'store',

components:{ //注册组件

AInput

},

data(){

return {

inputValue:''

}

}

}

</script>

实现过程input标签绑定handleInput事件,当input值修改时会触发input里的事件,从而执行handleInput方法,值的显示是通过value

兄弟之间通信

新建components组件 Ashow.vue

<template>

{{ content }}

</template>

<script>

export default{

props:{

content:{ // 属性value

type:[String,Number],

default:''

}

</script>

在store.vue引Ashow.vue注册组件

import Ashow from '_c/Ashow.vue'

<a-show :content="inputValue" />

<!----->

//跨文件之间如何通信:使用bus

定义文件夹bus,并创建index.js文件

import Vue from 'vue'//引入Vue

const Bus = new Vue()//创建实例

export default Bus//导出

然后在main.js把bus引入 import Bus from './bus'

Vue.prototype.$bus = Bus //在Vue的原型对象上添加Bus(把bus注册到根实例)

在之前Vue技术栈开发学习,Vue路由学习基础篇创建的email.vue添加

<button @click="handleClick">点击我</button>

export default{

methods:{

handleClick(){

this.$bus.$emit('on-click','hahaha')//传到bus

}

}

mount(){//生命周期

console.log(this.$bus)//创建一个空的bus实例,来作为交互的中介

}

}

在之前Vue技术栈开发学习,Vue路由学习基础篇创建的phone.vue用来接收email的事件

例如显示message

{{ message }}

export default{

data(){

return {

message:''

}

},

mount(){//生命周期

this.$bus.$on('on-click',mes=>{//bus事件监听

this.message = mes

})

}

}

优化bus

不把bus单独放一个文件夹 bus/index.js重命名为bus.js并一直lib文件夹下,引入是路径改为./lib/bus

宝宝起名-宝宝起名-更懂年轻父母的起名顾问


Guess you like

Origin blog.51cto.com/14775964/2665104