Vue2 学习记录--语法部分
学习资源--Vue2官网
Vue2停更后,发现官网原来的学习路径变成英文了,所以找到了中文简介进行学习:
简介 | Vue.js https://cn.vuejs.org/guide/introduction
一、模板语法
1.1 文本插值、html插值、属性和使用限制
在about组件中写测试代码。不废话,直接上代码。
<template><div class="about"><h1>This is an about page</h1>{{ msg }}<div v-html="htmTxt"></div><div v-bind:id="id" >百度</div><div :id="id" >百度</div><p>{{ count + 1 }}</p></div>
</template><script>
export default {name: 'HomeView',data() {return {msg: '<h2>静态文本</h2>',htmTxt:'<h2>静态文本</h2>',id: '1234',attr: 'test-id',count: 0,}}, components: { }
}
</script>
使用限制:
1、插值仅限于表达式。
2、关于缩写,当属性和属性名称相同时,比如 属性id,属性名称id,可以写成 :id, Vue2不支持。
1.2 简单的事件,用于测试语法
<template><div class="about"><h1>This is an about page</h1>{{ msg }}<div v-html="htmTxt"></div><div v-bind:id="id" >百度1</div><div :id="id" >百度2</div><div :testid = "testid">动态属性绑定</div><p>{{ count + 1 }}</p><p @click="myclick()">事件测试</p></div>
</template><script>
export default
{name: 'HomeView',data() {return {msg: '<h2>静态文本</h2>',htmTxt:'<h2>静态文本</h2>',id: '1234',testid: 'testid',count: 0,}}, methods: {myclick() {this.count += 1;console.log('点击事件');var s = document.getElementById("1234").innerHTML;alert(s)}},components: { }
}
</script>
1.3 指令:v-if、v-else、v-show
使用这几个指令控制dom显示,代码:
<template><div class="about"><h1>This is an about page</h1>{{ msg }}<div v-html="htmTxt"></div><div v-bind:id="id" >百度1</div><div :id="id" >百度2</div><div :testid = "testid">动态属性绑定</div><p>{{ count + 1 }}</p><p @click="myclick()">控制Dom显示</p><div v-if="count % 2 == 0">count是偶数</div><div v-else>count是奇数</div><div v-show="count % 2 == 0">v-show:count是偶数时显示</div></div>
</template><script>
export default
{name: 'HomeView',data() {return {msg: '<h2>静态文本</h2>',htmTxt:'<h2>静态文本</h2>',id: '1234',testid: 'testid',count: 0,}}, methods: {myclick() {console.log('点击事件');var s = document.getElementById("1234").innerHTML;alert(s)this.count += 1;}},components: { }
}
</script>
心得:
1、v-if 和 v-show都实现了dom元素的渲染控制,他们的差别是:v-if 是真正控制了dom内容的输出,即dom中有就显示没有就不显示;而v-show是通过display:none来控制元素的显示的。
2、<div v-if>模块如果使用 <template v-if >来替换,可以消除本身模块在dom中的占位。
