日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

Vuejs 写法实例

發布時間:2023/12/20 vue 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Vuejs 写法实例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原文地址:http://www.jianshu.com/p/293387d240b2

Hello World

<div id="app">{{ message }}<button v-on:click="clickMe()">點擊</button> <button v-on:click="clickMe">無參數的簡寫</button> </div> new Vue({el: '#app', data: { message: 'Hello Vue.js!' }, methods: { clickMe: function(){} } });

指令

循環

循環數組

<!-- Vue 1 這么寫 --> <li v-for="item in items"> 第{{ $index }}條:{{ item.message }}</li> <div v-for="item in items" track-by="id"> <!-- Vue 2 這么寫 --> <li v-for="(item, index) in items"> 第{{ index }}條:{{ item.message }}</li> <div v-for="item in items" v-bind:key="item.id">

循環對象

<!-- Vue 1 這么寫 --> <li v-for="(key, value) in obj"></li> <!-- Vue 2 這么寫 --> <li v-for="(value, key) in obj"></li>

循環數字

<span v-for="n in 10">{{ n }} </span> <!-- Vue 1 從0開始,Vue 2從1開始 -->

條件

<!-- 如果ok為false, 不輸出在 HTML 中 --> <div v-if="ok">Yes</div> <div v-else>No</div> <!-- 如果ok為false,只是 display:none 而已 --> <h1 v-show="ok">Hello!</h1>

事件綁定

<button v-on:click="say('hi')">點擊</button> <!-- 簡寫 --> <button @click="say('hi')">點擊</button> <!-- 傳入 event 對象 --> <button @click="say('hi', $event)">點擊</button> <!-- 阻止單擊事件冒泡 --> <button @click.stop="doSth">點擊</button> <!-- 阻止默認行為 --> <button @submit.prevent="doSth">點擊</button> <!-- 修飾符可以串聯 --> <a @click.stop.prevent="doThat"></a> <!-- 按鍵修飾符:回車時才會執行 --> <input @keyup.13="submit"><!-- 13 為 keycode --> <input @keyup.enter="submit"> <!-- 支持的全部按鈕為 enter, tab, delete, space, up, down, left, right 字母 -->

表單的雙向綁定

<input type="text" v-model="message"> <!-- 自定義選中值。否則 選中為value值,不選為空 --> <input type="checkbox" v-model="toggle" v-bind:true-value="a" v-bind:false-value="b">

綁定屬性

<div v-bind:class="{ 'class-a': isA, 'class-b': isB }"></div> <div v-bind:class="classArr"></div> <!-- classArr 是一個數組 --> <!-- 簡寫 --> <div :class="{ 'class-a': isA, 'class-b': isB }"></div> <div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> <img :src="imgSrc"> <a :href="baseURL + '/path'">

在 Vue 2 中,如果屬性值是變量,必須用綁定屬性的寫法。

// wrong <img src="{{imgSrc}}"> // right <img :src="imgSrc">

避免閃爍: v-cloak

[v-cloak] {display: none; } <div v-cloak>{{ message }} </div>

不會顯示?<div>?的內容,直到編譯結束。

單向綁定

單向綁定的意思是,即使綁定變量的值發生變化,顯示的內容仍舊就是最初綁定時候的值。

<!-- Vue 1 這么寫 --> <span>This will never change: {{* msg }}</span> <!-- Vue 2 不支持 -->

輸出 HTML

<!-- Vue 1 這么寫 --> <div>{{{ raw_html }}}</div> <!-- {{}} 中的 HTML 內容的會轉為純文本 --> <!-- Vue 2 這么寫 --> <div v-html="raw_html"></div>

計算屬性

<div id="demo">{{fullName}}</div> new Vue({data: {firstName: 'Foo', lastName: 'Bar' }, computed: { fullName: function () { return this.firstName + ' ' + this.lastName } } });

自定義指令

Vue.directive('my-directive', {bind: function () {// 準備工作 // 例如,添加事件處理器或只需要運行一次的高耗任務 this.el;// 添加指令的元素 this.vm.$get(name)// 獲得該指令的上下文 ViewModel this.expression;// 指令的表達式的值 }, update: function (newValue, oldValue) { // 值更新時的工作 // 也會以初始值為參數調用一次 }, unbind: function () { // 清理工作 // 例如,刪除 bind() 添加的事件監聽器 } }) <div v-my-directive="someValue"></div>

監聽數據變化

new Vue({data: {firstName: 'Foo' }, watch: { firstName: function (val, oldVal) { } } });

過濾器

{{ msg | capitalize }}// 'abc' => 'Abc'

常見內置過濾器
capitalize, uppercase, lowercase, json, limitBy, filterBy。所有見這里。

Vue 2 中把這些內置的過濾器都刪除了。

自定義過濾器

Vue.filter('wrap', function (value, begin, end) { return begin + value + end; }); <!-- 'hello' => 'before hello after' --> <!-- Vue 1 這么寫 --> <span v-text="message | wrap 'before' 'after'"></span> <!-- Vue 2 這么寫 --> <span v-text="message | wrap('before', 'after')"></span>

生命周期相關的鉤子函數

// Vue 1 new Vue({created: function(){}, beforeCompile: function(){}, compiled: function(){}, ready: function(){},// DOM 元素已經加入到HTML中 beforeDestroy: function(){}, destroyed: function(){} }); // Vue 2 new Vue({ created: function(){}, mounted : function(){},// 相對與 1 中的 ready beforeDestroy: function(){}, destroyed: function(){} });

過渡效果

<!-- Vue 1 這么寫 --> <div v-if="show" transition="my-transition"></div> <!-- Vue 2 這么寫 --> <transition v-bind:name="my-transition"> <!-- ... --> </transition> /* 必需 */ .my-transition-transition {transition: all .3s ease; } /* .my-transition-enter 定義進入的開始狀態 */ .my-transition-enter{} /* .my-transition-leave 定義離開的結束狀態 */ .my-transition-leave {}

組件

Vue 2 和 Vue 1 的組件的區別有些大。

Vue 1

定義和調用組件

<my-compprop="literal string":prop1="defaultOneWay":prop2.sync="twoWay" :prop3.once="oneTime"> </my-comp> Vue.component('my-comp', {template: 'html strings', props: { prop: String, prop1: { type: Number, required: true }, prop2: { type: Number, default: 88 }, // 對象/數組的默認值應當由一個函數返回 prop3: { type: Object, default: function () { return { msg: 'hello' } } }, // 自定義驗證函數 prop4: { validator: function (value) { return value > 10 } } }, data: functin(){ return { } } }

父子組件通信

// 子組件 var child = new Vue.component('child', { events: { 'parent-msg': function (msg) {} } }); // 子組件向父組件傳消息 child.$dispatch('child-msg', child.msg); // 父組件 var parent = new Vue({ events: { 'child-msg': function (msg) { // 父組件向所有子組件傳消息 this.$broadcast('parent-msg', 'received it'); } } });

this.$parent 訪問它的父組件。
this.$root 訪問它的根組件。
this.$children 訪問它的子組件。

小技巧

渲染一個包含多個元素的塊

<template v-for="item in items"> <li>{{ item.msg }}</li> <li class="divider"></li> </template> <template v-if="user"> <img :src="user.avatarUrl" alt=""> <div class="name">{{user.name}}</div> </template>

template 用于包含多個元素的塊,最終的渲染結果不會包含 template 元素。

Vue.set 和 Vue.delete

用于解決 不能檢測到屬性添加,屬性刪除的限制。

Vue.nextTick

// 修改數據 vm.msg = 'Hello' // DOM 沒有更新 Vue.nextTick(function () { // DOM 更新了 })

Vue 在檢測到數據變化時是異步更新 DOM 的。具體見?異步更新隊列。vm 上也有?this.$nextTick。

vue 插件

路由: vue-router

官方文檔

定義路由

var Vue = require('vue'); var VueRouter = require('vue-router'); Vue.use(VueRouter); router.map({ '/login': {component: require('login')}, '/user/:': {component: ...}, // 異步加載組件。加載器用的 webpack '/another': {component: function(resolve) { require.ensure([], function(require) { resolve(require('...')); }); }}, }); router.redirect({ '*': '/login' }); // 默認路由 router.beforeEach(function(transition) { // console.info('show loading'); transition.next(); }).afterEach(function(transition) { // console.info('hide loading'); }); // 啟動 router.start(Vue.extend({}), '#app');

使用路由

<a v-link.literal="/a/b/c"></a> <a v-link="{ path: Foo }">Go to Foo</a> new Vue({ready: function(){this.$route.path; this.$route.params; this.$route.query; }, methods: { jumpUrl: function () { // 代碼跳轉 this.$route.router.go('/a'); this.$route.router.go({ path: '/a', replace: true // 是否產生新的歷史記錄 }); this.$route.router.go({ name: 'a', // 具名路徑 params: {}, query: {} }); } } });

異步請求: vue-resource

官網

Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback); Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

攔截

Vue.http.interceptors.push(function(request, next) {var data = request.data;// 添加 url 前綴 request.url = serverPrefix + request.url; // 加請求參數 request.data.sessionid = localStorage.getItem('sessionid'); next(function (response) { if(登陸超時){ setTimeout(function () { router.go('/login'); }); } else { // modify response response.body = '...'; } }); });

支持 Promise

例如

Vue.http.post('/someUrl', [optinos]).then(function(res) { var data = res.data; return new Promise(function(resolve, reject) { if (!data.error) { reject() } else { resolve(data); } }.bind(this)); }) .then(function(res) { var data = res.data; return new Promise(function(resolve, reject) { Vue.http.post('/someUrl', data).then(function (res) { if(res.data){ resolve(); } }); }.bind(this)); }, failFn) .then(succFn, failFn);

其他

vm.$options.filters.filter名稱?可以獲取到具體的 filter

轉載于:https://www.cnblogs.com/raocheng/articles/6298018.html

總結

以上是生活随笔為你收集整理的Vuejs 写法实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。