Vue.js是构建渐进用户界面的框架,核心库只集中在视图层,而且容易上手。
如果你已经知道HTML,CSS和JavaScript,那么学习Vue是一件轻而易举的事! 在下面的文章中,将向您展示如何使用Vue,以及如何使用它来创建一个简单的UI版本的Hello World!
这是一个输入你的名称并显示的简单案例。
首先,需要添加< script src = "https://unpkg.com/vue/dist/vue.js" ></ script >到您的HTML。
下一步是设置应用程序的HTML容器。 这里使用一个<div>元素id="vue", 此容器将包含应用程序的所有HTML元素。
<div id="background"></div>
<div id="vue"> <h1>{{text}}</h1> <div v-html="html"></div> <div v-html="html1"></div> <bar></bar> <hello></hello> <button v-on:click="sayHi">Click Me</button> </div>
|
首先注意到{{text}},这是Vue的插值模版。如果你要获得Vue脚本运行的一个实例,只需要通过调用 new这个关键字。然后使用包含应用的html元素,这里是 id为vue的div元素 。
new Vue ( { el : "vue" } ) ;
|
接下来进行插值模版设置,添加一个数据属性,其值设置为包含模板名称和值的对象。 这里是{{text}},该代码如下所示:
new Vue ( { el : "vue" , data : { text : "some text" } } ) ;
|
这样你可以粘贴{{text}}到html任何位置,它就会显示“some text”刚才你要插入的东西是文本; 让我们假设你想插入任何HTML到您的应用程序。 要实现这一点,添加一个新的属性到Vue的data中。 它与上面的文本示例完全相同:
new Vue ( { el : "vue" , data : { html : "<p id='green'>You can use Vue to do<br/>all kinds of cool stuff!</p>" } } ) ;
|
html的插值模版有些区别,需要使用v-html,使其值等于新的属性,<div v-html="html"></div>接下来你会注意到这个案例中一些奇怪html,如 <bar> 和 <hello> ,这些事使用Vue创建自定义元素组件功能,要自己创建组件,你需要编写访问组件的方法javascript,你传递组建名称和一个包含模版属性的对象给Vue.component,模版属性值就是你要自定义的html元素,<hello > 的js代码如下:
Vue.component("hello", { template: "<label>Input Your Name:<h1></h1><input/></label>" });
|
最后,我们看看如何使用Vue的event handling事件处理,为了设置事件激活的调用函数,你应增加methods对象到Vue实例,对象包含名称与函数的键值对:
new Vue({ el: "vue", methods: { myFunction: function () { //do function stuff } } });
|
在html中,你会增加v-on属性到需要监听的html元素标签中,你能指定你要监听的事件类型。最后写入 methods的 key(也就是函数名称),上述案例是myFunction ,也就是:v-on:click="myFunction". 假设事件监听按钮,那么html代码是:
<button v-on:click="myFunction">Click Me</button>
这样,点击这个按钮,会激活上面的myFunction函数。
最后,回顾一下完整代码。Html如下:
<div id="background"></div>
< script src = "https://unpkg.com/vue/dist/vue.js " >< / script >
<div id="vue"> <h1>{{text}}</h1> <div v-html="html"></div> <div v-html="html1"></div> <bar></bar> <hello></hello> <button v-on:click="sayHi">Click Me</button> </div>
|
js代码:
//the following two blocks of code are components //we'll use them to make custom html elements
Vue.component("hello", { template: "<label>Input Your Name:<h1></h1><input/></label>" });
Vue.component("bar", { template: "<div id='bar'></div>" });
//next we'll select an element //set up data //and define a method
new Vue({ el: "vue", data: { text: "This is a Vue app.", html: "<p id='green'>You can use Vue to do<br/>all kinds of cool stuff!</p>", html1: "<p>Here we'll use Vue to make a an app<br/>that says Hello! to you.</p>" }, methods: { sayHi: function() { var name = document.querySelector("vue input"), button = document.querySelector("vue button"), prompt = "What's your name?"; var style = name.style;
if (!name.value || name.value === prompt) { name.value = prompt; name.focus(); } else { alert("Hello " + name.value + "!"); name.value = null; button.blur(); } } } });
|
A Friendly Introduction to Vue.js | appendTo