安卓vue

组件间传值

2021-12-16  本文已影响0人  云瑶糖糖
  1. 父子组件传值
    父传子

// 接收父组件传值

props:['name','age']

子传父

// 触发一个自定义事件

this.$emit('updateName',this.myName)
  1. 祖孙组件传值
    // 添加依赖数据,它里面定义的数据,子组件可以选择性注入并直接使用。
provide(){
    return {
        carName:this.carName,
        carPrice:this.carPrice,
        updateCarName:this.updateCarName,
        updateCarPrice:this.updateCarPrice
    }
}

// 注入祖级组件中的依赖数据,注意:跟props一样,接过来的数据是只读的,不能修改。

inject:['carName','carPrice','updateCarName','updateCarPrice']
  1. 兄弟组件传值
    // 在Vue是原型对象上,添加一个bus属性,该属性的的属性值是一个Vue实例。 // 将Vue的所有实例,都将共用同一个bus。

这个$bus属性,我们称之为:中央事件总线

Vue.prototype.$bus = new Vue()

//触发事件
this.$bus.$emit('getAddress',this.address)
//监听事件
this.$bus.$on('getAddress',(e)=>{
    this.address = e
})
  1. 全局状态管理
    如果想在不同的页面间实现传值,那就要使用全局状态管理了:

安装

npm install store

导入

//导入vuex插件
import Vuex from 'vuex'
//使用vuex插件
Vue.use(Vuex)

创建

//创建状态管理对象
let store = new Vuex.Store({
  //state选项,定义状态(状态就是数据)
  state:{
    planeName:'波音747',
    planePrice:'10Y'
  },
  //mutations选项,定义方法(注意:这里面只能定义同步方法)
  mutations:{
    //修改飞机的名称
    updatePlaneName(state,value){
      state.planeName = value
    },
    //修改飞机的价格
    updatePlanePrice(state,value){
      state.planePrice = value
    }
  }
})

使用

<!-- $store返回的是当前项目中的全局状态对象 -->
<h4>飞机信息:{{$store.state.planeName}},价格:{{$store.state.planePrice}}</h4>
//commit()方法,用于执行指定的mutations里面的方法
this.$store.commit('updatePlaneName','B52轰炸机')
this.$store.commit('updatePlanePrice','20Y')
上一篇 下一篇

猜你喜欢

热点阅读