el与data的两种写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>el与data的两种写法</title>
<!-- 引入vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<-- el与data的两种写法
1.el的两种写法:
(1).new Vue 的时候配置el属性
(2).先创建Vue实例,随后再通过vm.$mount('#root')指定el的值
2.data的两种写法
(1).对象式
(2).函数式
如何选择:目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则就会报错。
注意:由Vue管理的函数一定不要写箭头函数,一旦写了箭头函数,this就不是Vue实例了。
-->
<body>
<div id="root">
<h1>你好,{{name}}</h1>
</div>
<div id="root2">
<h1>你好,{{name}}</h1>
</div>
<script type="text/javascript">
// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false
// el的两种写法
const v = new Vue({
// el: '#root', 第一种写法
data: {
name: '小王',
}
})
console.log(v)
v.$mount('#root') // 第二种写法
new Vue({
el: '#root2',
// data 的第一种写法:对象式
/* data: {
name: '小友',
} */
// data 的第二种写法:函数式
// data: function(){
// console.log('--->', this) // 此处的this指的是Vuw实例对象
// return {
// name: '小友'
// }
// },
// 以上可简写为
data(){
return {
name: '小友',
}
}
})
</script>
</body>
</html>