zoukankan      html  css  js  c++  java
  • 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传值

    原文地址:https://segmentfault.com/a/1190000017362027

  • 相关阅读:
    html标签笔记
    C语言中的函数基础
    数组
    循环控制结构程序(goto、while、dowhile、 for)
    if语句+switch
    分支程序设计
    字符数据的输入与输出
    各类数值型数据之间的混合运算
    c语言概述及如何上机运行c程序
    [记录] Ubuntu 配置Apache虚拟站点
  • 原文地址:https://www.cnblogs.com/lalalagq/p/10114258.html
Copyright © 2011-2022 走看看