zoukankan      html  css  js  c++  java
  • Vue 子组件和父组件共用相同的值,在子组件中改变父组件会随时改变,在父组件中改变子组件中也会随时改变

    //父组件代码
    <
    template> <div> <input v-model="place"/> <button @click="updatePlace">修改input内容</button> <home-chil :place='place' @onChange="onChange" :width='inputWidth' @click.native="changeNative"/> // @click.native给组件绑定原生事件 </div> </template> <script> import HomeChil from './HomeChil' export default { name: "Home", data(){ return{ inputWidth:100, place:'输入框的值' } }, components:{ HomeChil }, methods:{ updatePlace(val){ this.place='父组件改变input中的内容'; this.inputWidth=this.inputWidth+100; },

    //传递给子组件得方法,子组件可以调用父组件中得这个方法 onChange(val){
    this.place=val }, changeNative(){ console.log('dd'); } } }; </script> <style> </style>

    //子组件中得代码
    <
    template> <div style="border:1px solid red">
          <span>当父组件件中的值改变我也会变为:{{inputName}}</span> 
        <input v-model="inputName" @change="onChangeInput" :style="style"/>
        <button @click="changeInput">改变input中的内容</button>
      </div>
    </template>
    
    <script>
    export default {
      name: "HomeChil",
      props:{
          Number,
          place:String,
      },
      data() {
        return {
          inputName: this.place
        };
      },
      computed:{
    //动态添加样式 style(){
    return{ this.width+'px' } } }, created() { }, watch: { place(val) { this.inputName = val; }, inputName(val) { this.$emit("onChange", val); } }, methods: { changeInput() { this.inputName = "子组件改变得值"; } } }; </script> <style> </style>

    注意:

           1.在组件设一个新变量,将父组件传过来的值赋值给新变量inputName:this.place  ;

           2.有时候,传递的数据并不是直接写死的,而是来自父组件的动态数据,这时可以使用指令V-bind来动态绑定props的值,并且在子组件中用watch 监听父组件中传过来的值,将值赋值给新变量,这时当父组件的数据变化时,也会传递给子组件。在子组件中用watch监听inputName,当它改变时调用父组件的方法onChange,将改变的值传给父组件,在父组件中将值赋值给place

    
    

         

  • 相关阅读:
    python中创建实例属性
    Python中if __name__ == "__main__": 的理解
    模块
    python函数式编程
    python-复杂生成式
    生成器的测试
    mysql乱码配置
    javascript
    Sql Server 2008 R2 下载地址
    Microsoft Data Access Components 2.8
  • 原文地址:https://www.cnblogs.com/lvlvlv/p/11642115.html
Copyright © 2011-2022 走看看