<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<title>Vue自學(xué):為什么組件data必須是個(gè)函數(shù)</title>
</head>
<body>
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
</div>
</body>
<!-- 所使用的template模板標(biāo)簽內(nèi),必須再嵌套一層div,否則會(huì)顯示不全 -->
<template id="cpn">
<div>
<h1>當(dāng)前計(jì)數(shù)值為:{{message}}</h1>
<button type="button" v-on:click="add">+</button>
<button type="button" v-on:click="reduce">-</button>
</div>
</template>
<script type="text/javascript">
//子組件
Vue.component('cpn',{
template:'#cpn',
//data必須是個(gè)函數(shù),原因是函數(shù)在復(fù)用時(shí)可以做到唯一性
//當(dāng)data不是一個(gè)函數(shù)的時(shí)候,組件標(biāo)簽在復(fù)用的時(shí)候,會(huì)使得數(shù)據(jù)重復(fù)錯(cuò)亂
data(){
return {
message:0,
}
},
methods:{
add(){
this.message++
},
reduce(){
this.message--
}
}
})
//父組件
const app = new Vue({
el:'#app',
data:{
},
methods:{
}
})
//為什么data需要是一個(gè)函數(shù)
//函數(shù)內(nèi)部本身是一個(gè)獨(dú)立的數(shù)據(jù)棧
// function test(x,y){
// let q = x;
// let w = y;
// console.log(q,w);
// }
// let obj1 = test(1,2)
// let obj2 = test(3,4)
// let obj3 = test(5,6)
// console.log(obj1,obj2,obj3)
//當(dāng)函數(shù)內(nèi)部引用的東西是外部常量時(shí),當(dāng)外部常量事先被更改后
//再次打印函數(shù),整個(gè)變量的值都會(huì)被改變
const obj = {
name:'wang xiao er',
age:'18',
}
function abc(){
return obj
}
let obj1 = abc()
let obj2 = abc()
let obj3 = abc()
obj1.name = 'koby'
console.log(obj1,obj2,obj3)
</script>
</html>
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)