计算属性computed:{}
computed里面声明的是变量,变量的值通过return获得。return 的值依赖于data中的属性 只要依赖的data发生变化 就会触发调用一次计算属性
<script>
let id = 0
export default {
data() {
return {
newTodo: '',
hideCompleted: false,
todos: [
{ id: id++, text: 'Learn HTML', done: true },
{ id: id++, text: 'Learn JavaScript', done: true },
{ id: id++, text: 'Learn Vue', done: false }
]
}
},
computed: {
filteredTodos(){
return this.hideCompleted ? this.todos.filter(t => !t.done):this.todos
}
},
methods: {
addTodo() {
this.todos.push({ id: id++, text: this.newTodo, done: false })
this.newTodo = ''
},
removeTodo(todo) {
this.todos = this.todos.filter((t) => t !== todo)
}
}
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo">
<button>Add Todo</button>
</form>
<ul>
<li v-for="todo in filteredTodos" :key="todo.id">
<input type="checkbox" v-model="todo.done">
<span :class="{ done: todo.done }">{{ todo.text }}</span>
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
<button @click="hideCompleted = !hideCompleted">
{{ hideCompleted ? 'Show all' : 'Hide completed' }}
</button>
</template>
<style>
.done {
text-decoration: line-through;
}
</style>
ref操作属性,生命周期之mounted(){}//组件已经挂载
生命周期详情: Vue.js (vuejs.org)
<script>
export default {
mounted(){
//组件已经挂载
this.$refs.p.textContent="77845K";
}
}
</script>
<template>
<p ref="p">hello</p>
</template>
侦听器watch:{valueName(newValue,oldValue){}
1.使用 watch 选项来侦听 valueName属性的变化。当 valueName改变时,侦听回调将被调用,并且接收新值newValue作为参数
<script>
export default {
data() {
return {
todoId: 1,
todoData: null
}
},
methods: {
async fetchData() {
this.todoData = null
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos/${this.todoId}`
)
this.todoData = await res.json()
}
},
mounted() {
this.fetchData()
},
watch:{
todoId(newId){
this.fetchData()
}
}
}
</script>
<template>
<p>Todo id: {{ todoId }}</p>
<button @click="todoId++">Fetch next todo</button>
<p v-if="!todoData">Loading...</p>
<pre v-else>{{ todoData }}</pre>
</template>
2.如果需要watch监听对象或数组的变化,则需要改写成下面这样子。
watch: {
list: {
deep: true,//深度监听
handler: function(newVal, oldVal) {
console.log('list数组改变了')
console.log('改变以后的值' + newVal)
console.log('改变以前的值' + oldVal)
},
}
}
因为对象或数组的引用地址没有变,所以无法获取改变之前的值,如确实需要知道改变之前的值,则需要单独监听。
watch: {
'list.value': {
handler: function(newVal, oldVal) {
console.log('list数组改变了')
console.log('改变以后的值' + newVal)
console.log('改变以前的值' + oldVal)
},
}
}