一. 计算属性与侦听属性
<template>
<div>
<h1>计算属性和侦听属性</h1>
<div>
{{ type + ':' + msg }}
</div>
<div>{{ type_msg }}</div>
<div>{{ firstName }}</div>
<div>{{ lastName }}</div>
<div>{{ fullName }}</div>
<div>{{ fullName }}</div>
<button @click="modifyFirstName">修改firstName</button>
<button @click="modifyLastName">修改lastName</button>
<button @click="modifyFullName">修改fullName</button>
<div>{{ getFullName() }}</div>
<div>语言: {{ language }}</div>
<button @click="switch1('ch')">中文</button>
<button @click="switch1('en')">English</button>
<div>{{ ZhangSan }}</div>
<div>{{ LiSi }}</div>
</div>
</template>
<script>
export default {
name: 'Demo7',
data () {
return {
a: '11',
msg: 'demo1',
type: 'news',
firstName: '孙',
lastName: '悟空',
language: 'ch',
ZhangSan: '',
LiSi: ''
}
},
computed: {
type_msg () {
return this.type + ':' + this.msg
},
fullName: {
get () {
return this.firstName + '' + this.lastName
},
set (newVal) {
const arr = newVal.split(' ')
this.firstName = arr[0]
this.lastName = arr[1]
}
}
},
methods: {
getFullName () {
return this.firstName + '' + this.lastName
},
modifyFirstName () {
this.firstName = '上官'
},
modifyLastName () {
this.lastName = '翠花'
},
modifyFullName () {
this.fullName = 'Michel Jordan'
},
switch1 (val) {
this.language = val
}
},
watch: {
language: {
handler (newVal) {
if (newVal === 'ch') {
this.ZhangSan = '张三'
this.LiSi = '李四'
} else if (newVal === 'en') {
this.ZhangSan = 'ZhangSan'
this.LiSi = 'LiSi'
}
},
immediate: true
}
}
}
</script>