vue的学习记录-例题

时间:2022-12-17 00:19:33

vue的学习记录

Hello World

html:

<div id="box">
{{message}} <!-- 输出的内容 -->
</div>

javascript:

window.onload = function(){
new Vue({ //创建一个vue实例
el: "#box", //为实例提供挂载元素
data: { //data对象
message: "hello world!"
}
})
}

双向绑定

html:

<div id="box">
<p>{{message}}</p>
<input type="text" v-model="message"> <!--实现表单和应用状态之间的双向绑定-->
</div>

javascript:

window.onload = function(){
new Vue({
el: "#box",
data: {
message: "hello world!"
}
})
}

vue的学习记录-例题

控制模块显示隐藏

html:

<div id="box">
<form action="">
<p v-if="!message">您还没有输入文字!</p> <!--此时v-if的值为true-->
<textarea v-model="message"></textarea>
<br>
<button v-show="message">Send Message</button> <!--此时v-show的值为false-->
</form>
</div>

javascript:

new Vue({
el: "#box",
data: {
message: "",
}
})

在这里,用v-if和v-show实现了相同的功能,但两者的实现原理不同,v-if在条件为true的时候,才会在浏览器里渲染出来;v-show不管条件为true还是false都会在浏览器里渲染出来,通过改变其display的值来显示隐藏元素。

事件、函数的调用及阻止默认事件

html:

<div id="box">
<form action="www.baidu.com" v-on:submit= "fun">
<button>提交{{message}}</button>
</form>
</div>

javascript:

    new Vue({
el: "#box",
data: {
message: 0,
},
methods: {
fun: function(ev){ //定义一个函数
this.message += 1;
ev.preventDefault(); //阻止默认事件
}
}
})

组件component的使用

html:

 <div class="box">
<counter heading="Links" color="hotpink"></counter>
<counter heading="Dislinks" color="yellowgreen"></counter>
</div>
<template id="temp">
<h1>{{heading}}</h1>
<button class="btn btn-primary" @click="count += 1" style="background:{{color}}">submit{{count}}</button>
</template>

javascript:

Vue.component("counter",{
template: "#temp",
props: ["heading","color"],
data: function (){
return {count : 0};
}
})
new Vue({
el: ".box"
})