vue 组件间传值

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
    原文地址: https://segmentfault.com/a/1190000017362027
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞