Vue2插槽、计算属性、监听

导读:本篇文章讲解 Vue2插槽、计算属性、监听,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

普通插槽

<slot>不传递里面放默认内容</slot>

在这里插入图片描述

具名插槽(插入到固定位置)

在这里插入图片描述

作用域插槽


//作用域插槽
<body>
  <div id="root">
    <child>
	  <!-- slote-scope接收数据props为变量名 在template里面使用props变量 -->
	  <template slot-scope='props'>
	    <h2>{{props.item}}</h2>
	  </template>
	</child>
  </div>
</body>
<script>
  Vue.component('child',{
    data:function(){
      return{
	    list:[1,2,3,4,5,6]
	  }
	},
	template:`<div>
	  <slot v-for="item of list" :item = item>
	  </slot>
	  </div>`
	});
    var vm = new Vue({
	  el:'#root'
	});
</script>

在这里插入图片描述

Vue2监听

// vue2监听
		watch:{
			sum:{
				immediate:true,//立即监听,执行一遍
				deep:true, //默认浅层次监听,开启深层次监听
				handler(newValue,oldValue){  //回调函数
					console.log("sum的值变化了",newValue,oldValue);
				}
			}
		}

Vue3监听

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://unpkg.com/vue@next"></script>
	</head>
	<body>
		<div id="app">
			<h1>当前是:{{sum}}</h1>
			<button @click="sum++">点我+1</button>
			<h1>当前是:{{msg}}</h1>
			<button @click="msg='123'">点我+1</button>
		</div>
	</body>
	<script>
			const app = Vue.createApp({
					setup() {
						const  { ref,watch } = Vue
						// setup函数里面this是underfined
						let sum = ref(0);
						let msg = ref('你好阿');
						//监视
						// 行为不用使用变量接收
						// 情况一
						watch(sum, (newValue, oldValue) => {
							console.log('sum变了', newValue, oldValue);
						})
						// 情况二
						watch(sum, (newValue, oldValue) => {
							console.log('sum变了', newValue, oldValue);
						},{immediate:true,deep:true});

						watch(msg, (newValue, oldValue) => {
							console.log('msg变了', newValue, oldValue);
						});
						// 情况三 监视ref所定义的多个响应式数据 
						watch([sum, msg], (newValue, oldValue) => {
							console.log('sum变了或msg变了', newValue, oldValue);
						});
						// 返回一个对象(常用)
						return {
							sum,
							msg
						}
					},
			});
			const vm = app.mount('#app');
	</script>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/4874.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!