账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vue2.0 父组件像子组件传值
    29
    0

    父组件

    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
      <conter num="10"></conter>
      </div>
    </template>
    <script>
    import conter from "./conter";
    export default {
      name: "HelloWorld",
      data() {
        return {
          msg: "Welcome to Your Vue.js App,test it111"
        };
      },
      components: {
        conter
      }
    };
    </script>

    子组件

    <template>
      <div>
          <button @click="add">+</button>
          <button @click="del">-</button>
          <p>{{num}}</p>
      </div>
    </template>
    
    <script>
    export default {
    props:["num"],
      data () {
        return {
           
        };
      },
      methods: {
          add(){
              this.num++
          },
          del(){
              this.num--
          }
      }
    }
    
    </script>

    点击子组件的按钮时报错:

    [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "num"
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 妖王大叔 普通会员 1楼

      在 Vue 2.0 中,父组件可以通过以下几种方式将值传递给子组件:

      1. 使用 props(属性): 父组件可以通过 props 从子组件中接收值,然后在子组件中通过 props 的方式传递给其他组件。

      示例: javascript // 父组件 export default { props: ['childData'], methods: { render() { return <ChildData childData={this.childData} />; } } };

      在子组件中,你可以通过 props 的方式访问到父组件传入的值。

      1. 使用 data:子组件也可以通过 data 属性从父组件中接收值。

      示例: javascript // 子组件 export default { data() { return { parentData: { name: '张三', age: 30, }, }; } };

      在父组件中,你可以通过 data 属性的值访问到子组件传入的值。

      1. 使用 eventBus:子组件也可以通过 eventBus 从父组件中接收值。

      示例: javascript // 父组件 export default { methods: { childData() { this.$emit('childData', this.childData); }, }, };

      在子组件中,你可以通过 eventBus 的方式接收到父组件传入的值。

      1. 使用 Vuex:Vue.js 的 store 也可以用来传递数据。

      示例: javascript // store.js export default { state: { parentData: { name: '张三', age: 30, }, }, mutations: { updateParentData() { this.parentData = { name: '张四', age: 40, }; }, }, actions: { updateParentData() { this.$store.dispatch('updateParentData'); }, }, };

      在子组件中,你可以通过 mutations 的值来更新父组件传入的值。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部