一、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!' } });
運行的效果如下: