指令练习的小例子1:
<!DOCTYPE html>
<html>
<head>
<title>vue指令</title>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<!--禁止二次渲染-->
<h1 v-once>{{title}}</h1>
<!-- 在网页中加载链接 -->
<h2>{{sayHello()}}-<a v-bind:href="link">vuejs</a></h2>
<!-- -->
<!-- 通过指令的方法添加链接 -->
<p v-html="finishedLink">baidu</p>
</div>
<script >
new Vue ({
el:'#app',
data:{
title:'hello world',
link:'https://cn.vuejs.org/v2/guide/index.html',
finishedLink:'<a href="http:www.baidu.com">baidu</a>'
},
methods:{
sayHello:function () {
this.title='hello !';
return this.title;
}
}
})
</script>
</body>
</html>
效果如下:
第二章作业:
效果如下:
HTML代码如下:
<!DOCTYPE html>
<html>
<head>
<title>test1</title>
<meta charset="utf-8">
<script src="vue.js"></script>
</head>
<body>
<div id="exercise">
<!-- 1) Fill the <p> below with your Name and Age - using Interpolation -->
<p>VueJS is pretty cool - {{name}} ({{age}})</p>
<!-- 2) Output your age, multiplied by 3 -->
<p>My age * 3 = {{age*3}}</p>
<!-- 3) Call a function to output a random float between 0 and 1 (Math.random()) -->
<p>{{random()}}</p>
<!-- 4) Search any image on Google and output it here by binding the "src" attribute -->
<div>
<img style="width:100px;height:100px" v-bind:src="image">
</div>
<!-- 5) Pre-Populate this input with your name (set the "value" attribute)预填充 -->
<div>
<input type="text" v-bind:value="name" >
</div>
</div>
<script >
new Vue({
el:'#exercise',
data:{
name:'Marry',
age:'23',
image:"http://img1.imgtn.bdimg.com/it/u=3987445628,2849740857&fm=200&gp=0.jpg"
},
methods:{
random:function(){
return Math.random();
}
}
})
</script>
</body>
</html>
出错地方:
data属性的值应该用引号裹着,通常用单引号,(双引号也可)不能直接写值;
如果文本插值没有按预期结果显示,原因很可能是代码中出现了语法错误,比如多了一个尖括号,或者括号位置不对等等;
产生随机数用到了Math.random()函数 ;
给文本框预填充值时需要用到v-bind指令来绑定value属性。