標籤:
組件(Component)是 Vue.js 最強大的功能之一。組件可以擴充 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自訂元素,Vue.js 的編譯器為它添加特殊功能。今天我們就來學習一下。
vue中的重要特性一、vue中的自訂群組件
html的代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>vue1</title> <script type="text/javascript" src="../vue.js"></script></head><body> <div id="app"> <my-component my-name="huhx"></my-component> </div> <script type="text/javascript" src="js/vue3.js"></script></body></html>
vue3.js的代碼:
// 定義var MyComponent = Vue.extend({ template: ‘<div>A custom component!{{myName}}</div>‘, props: [‘myName‘]})// 註冊Vue.component(‘my-component‘, MyComponent);// 建立根執行個體var ap = new Vue({ el: ‘#app‘,})
運行效果如下:
二、vue中的自訂指令
html的代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>vue4</title> <script type="text/javascript" src="../vue.js"></script></head><body> <div id="app"> <div v-my-directive="someValue">{{msg}}</div> </div> <script type="text/javascript" src="js/vue4.js"></script></body></html>
vue4.js:
Vue.directive(‘my-directive‘, { bind: function() { // 準備工作 console.log("bind function."); }, update: function(newValue, oldValue) { // 值更新時的工作 console.log("new: " + newValue + ", old: " + oldValue); }, unbind: function() { // 清理工作 console.log("unbind function."); }});var demo = new Vue({ el: ‘#app‘, data: { msg: ‘hello!‘ }})
啟動並執行效果:
console列印的日誌:
bind function.new: undefined, old: undefined
三、vue中的自訂過濾器
html的代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>vue5</title> <script type="text/javascript" src="../vue.js"></script></head><body> <div id="app"> <span v-text="message | reverse"></span> </div> <script type="text/javascript" src="js/vue5.js"></script></body></html>
js的代碼如下:
Vue.filter(‘reverse‘, function (value) { return value.split(‘‘).reverse().join(‘‘)});var demo = new Vue({ el: ‘#app‘, data: { message: ‘hello!‘ }});
啟動並執行效果如下:
友情連結
Vue基礎---->VueJS的使用(二)