Vue slots, custom directives, render functions, filters and plugins

Table of contents

slot

Custom instructions

directive

Global registration

partial registration

hook function

renderrendering function

filter

plug-in

plugin


slot

Ordinary slot, named slot, scoped slot

Slots allow us to pass templates to child components when they are called.

The <slot> element serves as an outlet for hosting distributed content. A <slot> outlet without a name will have the implicit name "default".

Everything in the parent template is compiled in the parent scope; everything in the child template is compiled in the child scope.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

</head>
<body>
    <div id="app">
        <my-a>
            {
   
   {msg}}
            <!-- 父组件调用子组件提供了一个模版 -->
            <div :title="msg">我是块级元素</div>
            <img width="150px" src="../../HTML&CSS/images/ad10.jpg">

            <!-- <header>头部内容</header>
            <article>中间内容</article>
            <footer>底部内容</footer> -->
            <!-- 父组件调用子组件提供了具体的模版 -->
            <!-- <template v-slot:header> -->
            <!-- 绑定具名插槽时可以简写为#header -->
            <template #header>
            <!-- <template v-slot:header> -->
            <h1>头部的内容</h1>
            </template>
            <template v-slot:article>
                <p>我是文章内容</p>
                <p>我是文章内容</p>
            </template>
            <template v-slot:footer>
                <div>我是底部的内容</div>
            </template>
            <!-- 作用域插槽 -->
            <template v-slot:default="scope">
            <!-- <template v-slot="scope"> -->
            <!-- <template slot-scope = "scope"> -->
                <div>
                    {
   
   {scope}}
                </div>
            </template>
        </my-a>
    </div>
    <script>
        let myA = {
            template:`
                <div>
                    myA组件
                    <slot name='default'>submit</slot>
                    <hr>
                    <header>
                        <slot name='header'></slot>
                    </header>
                    <article>
                        <slot name='article'></slot>
                    </article>
                    <footer>
                        <slot name='footer'></slot>
                    </footer>
                    <slot v-bind:subMsg='subMsg'></slot>
                </div>
            
            `,
            data(){
                return{
                    msgA:'我是子组件',
                    subMsg:'我是子组件的属性'
                }
                
            }
        }
        new Vue({
            components:{
                'my-a':myA
            },
            el:'#app',
            data:{
                msg:'我是父组件中msg',
            },
            methods:{},
        })
    </script>
</body>
</html>

 

 

Custom instructions

directive

Many instructions in Vue are called with v-. However, sometimes the instructions provided by Vue do not meet our needs. At this time, we need to customize the instructions.

Directives allow us to perform low-level operations on ordinary DOM elements. Can be registered globally or locally

Global registration

Using Vue.directive

partial registration

Add new options directives to Vue instances or components

hook function

Hook functions can add code at key moments in the instruction's life cycle

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
    <div id="app">
        <input v-focus="msg" type="text" >
        {
   
   {msg}}
        <input v-myshow="msg" type="text" >
    </div>
    <script>
        Vue.directive('focus',{
            inserted(el){
                el.focus()
            },
            bind(el,binding,vnode){
                el.style.backgroundColor=binding.value
            }
        })
        new Vue({
            directives:{
                'myshow':{
                    inserted(el){
                    },
                    bind(el,binding,vnode){
                        el.value=binding.value;
                    }
                }
            },
            el:"#app",
            data:{
                msg:'red'
            },
            methods:{}
        })
    </script>
</body>
</html>

renderrendering function

Vue recommends using templates to create your HTML in most cases. However, there are some scenarios where you really need the full programming capabilities of JavaScript. At this time you can use rendering functions , which are closer to the compiler than templates.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <my-a  :friuts="friuts">
            列表
        </my-a>
    </div>
    <script>
        let myA={
            props:{
                friuts:{
                    type:Array,
                }
            },
            beforeMount(){
                alert('beforeMount')
            },
            mounted(){
                alert('mounted')
            },
            render(h){
                alert('2222')
                let lis=this.friuts.map(item=>{
                    return h('li',{},item)
                })
                return h('ul',{},[this.$slots.default,...lis])
            },
            // template:`
            //  <div>
            //      <ul>
            //          <li v-for='item in friuts'>{
   
   {item}}</li>    
            //      </ul>
            //  </div>
            // `,
            data(){
                return {
                    
                }
            }
        }
        new Vue({
            components:{
                'my-a':myA
            },
            el:"#app",
            data:{
                friuts:['苹果','香蕉','菠萝']
            },  
            methods:{}
        })
    </script>
</body>
</html>

filter

Vue.js allows custom filters that can be used for some common text formatting. Filters can be used in two places: double curly brace interpolation and v-bind expressions (the latter is supported starting from 2.1.0+). Filters should be added at the end of the JavaScript expression, |indicated by the "pipe" symbol:

<!-- In double curly braces --> { { message | filterMethod }} <!-- In `v-bind` -->

​​

//首先引入 `moment`第三方库,再进行接下来的操作。引入moment仅供实现功能,与过滤器没有关系。
<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/locale/af.js"></script>
<script>
    // 全局注册
    Vue.filter("fmtDate_global", function (date) {
        return moment(date).format("YYYY-MM-DD HH:mm:ss");
        // 或者return自己编写的时间处理函数
    })
    new Vue({...})
</script>
<!DOCTYPE html>
<html lang="en">
​
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello world</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
​
<body>
  <div id="app">
    <!-- 使用过滤器 -->
    <div>{
   
   { new Date() | fmtDate_global}}</div>
    <div :title="new Date() | fmtDate_global">鼠标悬停查看时间</div>
  </div>
  <script>
    // 全局注册过滤器
    Vue.filter("fmtDate_global", function (date) {
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
     
    })
    new Vue({
      el: '#app',
    })
  </script>
</body>
​
</html>

plug-in

plugin

Plugins are often used to add global functionality to Vue. Vue.js plugins should expose an install method. The first parameter of this method is the Vue constructor, and the second parameter is an optional options object:

MyPlugin.install = function (Vue, options) { 
// 1. Add a global method or property 
Vue.myGlobalMethod = function () { 
 // Logic... 
} 
​//
2. Add a global resource 
Vue.directive('my- directive', { 
 bind (el, binding, vnode, oldVnode) { 
   // Logic... 
 } 
 ... 
}) 
​//
3. Inject component options 
Vue.mixin({ 
 created: function () { 
   // Logic. .. 
 } 
 ... 
}) 
​//
4. Add instance method 
Vue.prototype.$myMethod = function (methodOptions) { 
 // Logic... 
} 
}

Use plugins via global methods Vue.use(). It needs to be done before you call new Vue()to start the application:

// Call `MyPlugin.install(Vue)` 
Vue.use(MyPlugin) 
​new
Vue({ 
// ...component options 
})
<!DOCTYPE html>
<html lang="en">
​
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
​
</head>
​
<body>
    <div id="app">
        {
   
   {time | fmtTime}}
        <input type="text" v-focus>
    </div>
    <script>
        let MyPlugin = {
            install(Vue, options) {
                Vue.filter('fmtTime', (val) => {
                    return moment(val).format('YYYY--MM-DD')
                }),
                Vue.prototype.$message=function(val){
                    alert(val)
                },
                    Vue.directive('focus', {
                        inserted(el) {
                            el.focus()
                        },
                        bind(el, binding, vnode) {
                            el.style.backgroundColor = binding.value
                        }
                    })
            },
        };
        Vue.use(MyPlugin)
        new Vue({
            el: "#app",
            data: {
                time: new Date().getTime()
            },
            created(){
                this.$message('请求成功')
            },
            methods: {}
        })
    </script>
</body>
​
</html>

Guess you like

Origin blog.csdn.net/qq_53866767/article/details/132111757