Vue-快速入门

151 阅读2分钟

MVVM

model-view-modelview 是MVC 的改进版,前后端分离

Vue

只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合,也能够为复杂的单页应用提供驱动

所有东西都是响应式的,在控制台修改对应属性,会实时更新

使用

导入

在idea中添加vue插件

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

模板

定义变量

 var vm3=new Vue({
        el:"#app2",
        data:{"message":"132",
                "sex":"",
                "select":""},
        methods:{
        say:function (event) {
                alert("1");
            }
        }
    });

el:代表选择的组件

data:以键值对的方式传递数据

methods:自定义方法,say为方法名

获取数据

<div id="app">
    <h1> {{message}}</h1>
    <button v-on:click="say" >click me</button>
</div>

通过{{变量名}}获取数据

v-bind

单向绑定元素特性

<span v-bind:title= "message">鼠标悬浮查看</span>

效果:鼠标悬浮在文字上可显示message对应的数据即"132" 通过控制台修改message的值可以修改悬浮显示的文字

v-model

实现表单输入和应用状态之间的双向绑定

<div id="app2">
    <input type="text" v-model="message">{{message}}
    <input type="radio" value="man" name="sex" v-model="sex">
    <input type="radio" value="woman" name="sex" v-model="sex">
    {{sex}}
    <select v-model="select">
        <option disabled value="" >---请选择---</option>
        <option value="A" >A</option>
        <option value="B" >B</option>
        <option value="C" >C</option>
    </select>
    {{select}}
</div>
 var vm3=new Vue({
        el:"#app2",
        data:{"message":"132",
                "sex":"",
                "select":""},
        methods:{}
    });

效果:当文本框中的数据变更时,其右侧的数据也会实时变化,无需打开控制台

条件判断与循环控制

<div id="hello">
    <span v-bind:title= "message">鼠标悬浮查看</span>
<!--    <h1> {{message}}</h1>-->
    <span v-if="statue=='ok'">ok</span>
    <span v-else-if="statue=='no'">no</span>
    <span v-else>nothing</span>
    <li v-for="item in items">
        {{item}}
    </li>
</div>
var vm=new Vue({
        el: "#hello",
        data:{"message": "hello vue",
            "statue":"ok",
            "items":[{"hello":"hello world"},{"hello2":"hello vue"}]
        }
    });

效果: 通过修改statue的属性变更显示的数据 遍历items(注:v-for="item in items" {{item}})

组件

组件系统是 Vue 的另一个重要概念,因为它是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用

一个组件本质上是一个拥有预定义选项的一个 Vue 实例

// 定义名为 todo-item 的新组件
//定义需放在 var vm=new Vue(……)之前才生效
Vue.component('todo-item', {
  template: '<li>这是个待办项</li>'
})

//使用todo-item,使用自定义组件需在被vue绑定的元素内
<div id="app">
<todo-item></todo-item>
</div>

与for循环的结合

Vue.component('todo-item', {
//"prop",类似于一个自定义 attribute。
        props:['attribute'],
        template: '<li>{{attribute}}</li>'
    });
var app7 = new Vue({
        el: '#app-7',
        data: {
            items: [
                { id: 0, text: '蔬菜' },
                { id: 1, text: '奶酪' },
                { id: 2, text: '随便其它什么人吃的东西' }
            ]
        }
    })
<div id="app-7">
   <todo-item v-for="item in items" v-bind:attribute="item"></todo-item>
</div>