14

1、父组件给子组件传值

父组件:

<template>
   <child :name="name"></child>
</template>
<script>
import child from "./child.vue"
  export default {
     components: {child},
     data(){
      return {name:"二哈"}
     }
  }
</script>

子组件:

<template>
  <div>{{name}}</div>
</template>
<script>
  export default {
    props:["name"]
  }
</script>

2、子组件给父组件

父组件:

<template>
  <child @childToParent="reviceSondata"></child>
</template>
<script>
import child from "./child.vue"
  export default {
    components: {child},
    methods:{
      reviceSondata(data){
        console.log(data);
      }
    }
  }
</script>

子组件:

<template>
   <button @click="dataTofather">点击</button>
</template>
<script>
  export default {
    data () {
      return {
        message: '啦啦啦啦'
      }
    },
    methods:{
      dataTofather(){
        this.$emit("childToParent",this.message,true);
      }
    }
  }
</script>

3、vuex

store.js:

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

Vue.use(Vuex)

const store = new Vuex.Store({
  // 定义状态
  state: {
    headImg: JSON.parse(sessionStorage.getItem('headImg')) || ""
  },
  mutations: {
    newImg(state, msg){
      sessionStorage.setItem('headImg', JSON.stringify(msg))
      state.headImg = msg;
    }
  }
})

export default store

main.js中引入vuex

import Vue from 'vue';
import Vuex from 'vuex';
import store from './vuex/store';
Vue.use(Vuex);
var v = new Vue({
  el: '#app',
  router,
  store,
  components: {index},
  template: '<index/>',
  created: function () {

  }
})

传值:this.$store.commit("newImg", value);
取值:this.$store.state.headImg

github地址:vue传值


Rossy1
2.1k 声望2.5k 粉丝

做大娱乐家!