zoukankan      html  css  js  c++  java
  • uniapp

    .sync修饰字在vue1.0作为双向数据绑定而存在,在2.0时被砍掉。而后在2.3被当做语法糖加入 (vue单向绑定数据流通)

     

    假设一个需求是:父组件值传入到子组件,然后子组件更改后父组件的值也得更改

     

    1. 通过props传值,data赋值的操作实现(避免出现双向数据绑定错误)

    index.vue

    <template>
    	<view class="content">
    		<onA :number.sync="num"></onA>
    		父组件:{{num}}
    	</view>
    </template>
    
    <script>
    	import onA from '@/components/onA.vue';
    	export default {
    		data() {
    			return {
    				num: 10
    			}
    		},
    		components: {
    			onA
    		},
    		onLoad() {},
    		mounted() {
    
    		},
    		methods: {
    		}
    	}
    </script>
    
    <style>
    	.title {
    		color: #007AFF;
    	}
    </style>

     

    onA.vue

    <template>
    	<view @click="fn">
    		子组件:
    		{{numberCache}}
    	</view>
    </template>
    
    <script>
    	export default {
    		data() {
    			return {
    				numberCache: null
    			}
    		},
    		props: ['number'],
    		created() {
    			this.numberCache = this.number;
    		},
    		methods: {
    			fn() {
    				// 这里处理它就好
    				this.numberCache++;
    				this.$emit('update:number', this.numberCache);
    			}
    		},
    		mounted() {
    
    		}
    	}
    </script>
    
    <style lang="scss" scoped>
    	.title {
    		color: #F0AD4E;
    	}
    </style>
    

      

    我们也可以利用子组件this.$emit传值再赋值的形式去更新父组件的值.

    2. 如果不想引起双向数据绑定报错可以通过ref标识向子组件赋值


    index.vue(父组件)

    <template>
    	<view class="content">
    		<onA :number.sync="num" ref="on"></onA>
    		父组件:{{num}}
    	</view>
    </template>
    
    <script>
    	import onA from '@/components/onA.vue';
    	export default {
    		data() {
    			return {
    				num: 10
    			}
    		},
    		components: {
    			onA
    		},
    		onLoad() {},
    		mounted() {
    			this.$refs.on._data.number = this.num;
    		},
    		methods: {}
    	}
    </script>
    
    <style>
    	.title {
    		color: #007AFF;
    	}
    </style>
    

    onA.vue

    <template>
    	<view @click="fn">
    		子组件:
    		{{number}}
    	</view>
    </template>
    
    <script>
    	export default {
    		data() {
    			return {
    				number: null
    			}
    		},
    		methods: {
    			fn() {
    				this.number++;
    				this.$emit('update:number', this.number);
    			}
    		},
    		mounted() {
    
    		}
    	}
    </script>
    
    <style lang="scss" scoped>
    	.title {
    		color: #F0AD4E;
    	}
    </style>
    

      

  • 相关阅读:
    UpdateBatch到底是怎么用的?
    进度条在.net导入Excel时的应用实例
    asp.net页面触发事件panel滚动条高度不变的实现方法
    .NET中的枚举用法浅析
    .NET程序调试技巧(一):快速定位异常的一些方法
    ASP.NET实现推送文件到浏览器的方法
    微软官方SqlHelper类 数据库辅助操作类
    Asp.net中使用文本框的值动态生成控件的方法
    ASP.NET中Dictionary基本用法实例分析
    ASP.NET动态增加HTML元素的方法实例小结
  • 原文地址:https://www.cnblogs.com/cisum/p/12196878.html
Copyright © 2011-2022 走看看