2

Vue技术栈开发学习之状态管理bus的使用

 3 years ago
source link: https://segmentfault.com/a/1190000039668165
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Vue技术栈开发学习之状态管理bus的使用

发布于 今天 15:04

1新建组件store.vue,在路由列表注册,并在components目录下新建一个组件AInput.vue(自己 创建的组件最好带上前缀)

path:'/store',

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

components的AInput.vue

<template>

<input @input="handleInput" :value="value">//绑定input事件和value值

</template>

<script>

export default{

name:'AInput',

props:{

value:{ // 属性value

type:[String,Number],

default:''

methods:{

handleInput(event){

const value = event.target.value//获取文本框输入值

this.$emit('input',value)//把获取到的值传出去

//注意为什么不能直接在这里修改value值,这是vuex强调的单向数据流,父级组件之间传值,值的修改一定是通过父组件,如果向组件与子组件传值一定是通过属性,而子组件想修改父组件传来的值一定要通过事件方式来修改

</script>

store.vue

<template>

<div>

//使用input组件

<a-input v-model='inputValue' />//v-model双向绑定(相当于语法糖,相当于 :value="inputValue" @input="handleInput")

{{ inputValue }}//显示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.bus.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.bus.bus.on('on-click',mes=>{//bus事件监听

this.message = mes

优化bus

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

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK