methods
- 普通业务处理
适用于业务逻辑处理,数据不能缓存,每次使用都会重新调用
watch
- 单个数据、路由
适合监听单个数据的变化,也可以监听路由的变化
computed
- 属性计算 computed里面定义的函数可以直接当做属性使用
适合计算属性,可以缓存数据
- 示例:
<body>
<div id="app">
<input type="text" v-model="firstname"> -
<input type="text" v-model="lastname"> =
<!-- <input type="text" :value="fullname()"> -->
<!-- {{fullname()}}
{{fullname()}} -->
<input type="text" :value="fullname">
{{fullname}}
{{fullname}}
</div>
<script>
new Vue({
el: "#app",
data: {
firstname: '',
lastname: '',
// fullname: ''
},
created() {
},
methods: {
// fullname() {
// console.log(1)
// return this.firstname + '-' + this.lastname
// }
},
// 监听存在的数据
watch: {
// firstname(newVal, oldVal) {
// // console.log(newVal, oldVal)
// // this.fullname = this.firstname + '-' + this.lastname
// this.fullname = newVal + '-' + this.lastname
// },
// lastname(newVal, oldVal) {
// // console.log(newVal, oldVal)
// this.fullname = this.firstname + '-' + newVal
// }
},
computed: {
// computed里面定义的函数可以直接当做属性使用
fullname() {
console.log(1)
return this.firstname + '-' + this.lastname
}
}
})
</script>
</body>
watch监听路由
<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">
<title>Document</title>
<script src="./lib/vue.js"></script>
<script src="./lib/vue-router.js"></script>
</head>
<body>
<div id="app">
{{msg}}
<router-link to="/login">login</router-link>
<router-view></router-view>
</div>
<script>
const Login = {
template: '<div>login组件</div>'
}
const Home = {
template: '<div>Home组件</div>'
}
const router = new VueRouter({
routes: [
{
path: '/',
component: Home
},
{
path: '/login',
component: Login
}
]
})
new Vue({
el: "#app",
data: {
msg: ''
},
created() {
},
methods: {
},
router,
watch: {
'$route.path'(newVal, oldVal) {
// console.log(newVal, oldVal)
if (newVal === '/login') {
console.log('欢迎进入登录页面')
this.msg = '欢迎进入登录页面'
} else if (newVal === '/') {
this.msg = '来了老弟'
}
}
}
})
</script>
</body>