computed:计算属性
watch
1、案例1
<template>
<div>
<div style="margin-bottom:15px;">
Your roles: {{ roles }}
</div>
Switch roles:
<el-radio-group v-model="switchRoles">
<el-radio-button label="editor" />
<el-radio-button label="admin" />
</el-radio-group>
</div>
</template>
<script>
export default {
computed: {
roles() {
return this.$store.getters.roles
},
switchRoles: {
get() {
return this.roles[0]
},
set(val) {
this.$store.dispatch('user/changeRoles', val).then(() => {
this.$emit('change')
})
}
}
}
}
</script>
2、案例2
<template>
<div style="display:inline-block;">
<label class="radio-label">Book Type: </label>
<el-select v-model="bookType" style="width:120px;">
<el-option
v-for="item in options"
:key="item"
:label="item"
:value="item"
/>
</el-select>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: 'xlsx'
}
},
data() {
return {
options: ['xlsx', 'csv', 'txt']
}
},
computed: {
bookType: {
get() {
return this.value
},
set(val) {
this.$emit('input', val)
}
}
}
}
</script>
3、案例3
<div id="demo">{{ fullName }}</div>
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
4、案例4
<template>
<div class="app-container">
<div>{{ fullName }}</div>
<br><br><br><br><br><br><br>
<div>
<button @click="add()">计数</button>
总价为:{{price}}
</div>
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'Foo',
lastName: 'Bar',
package1: {
count: 1,
price: 123
},
}
},
computed: {
fullName: {
get: function () {
return this.firstName + ' ' + this.lastName
},
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
},
price: function() {
return this.package1.count * this.package1.price
}
},
methods: {
add: function(){
this.package1.count++
}
}
}
</script>
*
*
*
*
*
*
*
*