Registration and usage scenarios of filters, custom instructions, and components

Write them together because they are divided into two types - local registration and global registration.

It should be noted that the key words used in the local registration (with s) and the global registration (without s) of the three are similar, please pay attention to the distinction.

In addition, the global registration of filters, global registration of custom instructions and global registration of components must be written before the Vue instance. For details, please see:  https://blog.csdn.net/weixin_55992854/article/details/119107461

Table of contents

filter

partial registration

global registration

expand

      1. The filter can pass parameters

      2. Filters can be used in series

custom directive

partial registration

global registration

components

what is a component

Component Features

Classification and use of components

global registration

partial registration


filter

  • Role: processing data format

  • Where to use: double curly braces interpolation and v-bind expressions (the latter is supported from 2.1.0+).

  • Classification: Local Registration and Global Registration

partial registration

  1. Configure the filter filters in the options of the Vue instance object: {}

  2. Filter name: (data to be filtered)=>{return filtered result}

  3. Use filters in views: { {filtered data | filter name}

<body>
    <div id="app">
        <p>处理前:{
   
   {msg}}</p>
        <!-- 3. 调用过滤器 -->
        <p>处理后:{
   
   {msg | toUpper}}</p>
    </div>
    <div id="aaa">
        <p>处理前:{
   
   {msg}}</p>
        <p>处理后:{
   
   {msg | toUpper}}</p>
    </div>
</body>

<script src="./vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            msg: 'kfc'
        },
        // 1. 设置vue实例的过滤器filters选项
        filters: {
            toUpper: function(v) {
                // 2. 在过滤器的方法中操作数据并返回结果
                return v.toUpperCase();
            }
        }
    });
</script>

Note: Locally registered filters are only applicable to the current Vue instance object

global registration

  1. Define the global filter Vue.filter() before creating the Vue instance

  2. Vue.filter('filter name', (data to be filtered) => {return the result of data processing});

  3. Use filters in views via { {data | filter name}} or v-bind

<body>
    <div id="app">
        <p>处理前:{
   
   {msg}}</p>
        <!-- 3. 调用过滤器: (msg会自动传入到toUpper中)-->
        <p>处理后:{
   
   {msg | toUpper}}</p>
    </div>
    <div id="aaa">
        <p>处理前:{
   
   {msg}}</p>
        <p>处理后:{
   
   {msg | toUpper}}</p>
    </div>
</body>

<script src="./vue.js"></script>
<script>
    // 1. 定义全局过滤器
    Vue.filter('toUpper', (value) => {
        console.log(value);
        // 2. 操作数据并返回
        value = value.toLowerCase();
        console.log(value);
        return value;
    });

    new Vue({
        el: '#app',
        data: {
            msg: 'hello'
        },
    });
    new Vue({
        el: '#aaa',
        data: {
            msg: 'hello'
        },
    });
</script>

Note: Globally registered filters can be used by different Vue instance objects

expand

      1. The filter can pass parameters

<div id="app">
    {
   
   {count | toD("元")}}
</div>

<script src="../js/vue.js"></script>
<script>
    //(v,y)中v指的是被处理的数据count,y指的是自己传入的参数("元")
    Vue.filter("toD", (v, y) => {
        console.log(v);
        console.log(y);
        return "$" + v + y;
    });


    new Vue({
        el: "#app",
        data: {
            count: 100,
        },
    });
</script>

      2. Filters can be used in series

<div id="app">
    <!-- 
        2.串联使用 
        {
   
   {被处理的数据 | 过滤器A | 过滤器B}}
        注意: 过滤器A处理的是count
        过滤器B处理的是过滤器A所返回的结果
    -->
    {
   
   {count | A | C("元")}}
</div>

<script src="../js/vue.js"></script>
<script>

    Vue.filter("A", (v) => {
        return "$" + v;
    });
    Vue.filter("C", (v, y) => {
        console.log(v);//$100
        return v + y;
    });

    new Vue({
        el: "#app",
        data: {
            count: 100,
        },
    });
</script>

custom directive

  • Usage scenario: Need to operate on ordinary DOM elements, at this time, custom instructions will be used

  • Classification: Global Registration and Local Registration

partial registration

  1. Set the custom instruction directives in the options of the Vue instance object:{}

  2. directives:{'The core name of the instruction':{ inserted: (DOM object when using the instruction) => {specific DOM operation} }}

  3. Use directives in views via tags

<div id="app">
    <!-- 3. 在视图中通过标签去使用指令 -->
    <input v-focus type="text">
</div>

<script src="./vue.js"></script>
<script>
    new Vue({
        el: '#app',
        // 1. 在vm对象的选项中设置自定义指令 directives:{}
        directives: {
            // 2. directives:{'指令的核心名称':{ inserted: (使用指令时的DOM对象) => { 具体的DOM操作 } }}
            focus: {
                // 指令的定义
                inserted: function(el) {
                    el.focus();
                }
            }
        }
    });
</script>

Note: It can only be used in the view managed by the vue instance where this option is located

global registration

  1. Define the global custom directive Vue.directive() before creating the Vue instance

  2. Vue.directive('directive name', { inserted: (DOM object using the directive) => { specific DOM operation} } );

  3. Use "v-custom command name" in the view to use the command

<div id="app">
    <!-- 3. 在视图中通过标签去使用指令 -->
    <input v-focus type="text">
</div>

<script src="./vue.js"></script>
<script>
    // 全局自定义指令
    // 1.在创建 Vue 实例之前定义全局自定义指令Vue.directive()
    // 2. Vue.directive('指令的核心名称',{ inserted: (使用指令时的DOM对象) => { 具体的DOM操作 } } );
    Vue.directive('focus', {
        // 当被绑定的元素插入到 DOM 中时,inserted会被调用
        inserted: (el) => {
            // el 就是指令所在的DOM对象
            el.focus();
        }
    });

    new Vue({
        el: '#app'
    });
</script>

Vue.directive (custom directive name) does not need to add v- when using custom directives need to add v-

inserted: When the bound element is inserted into the DOM, it will be called

components

what is a component

Requirements: If there are multiple controls with the same structure in the page, such as

<div id="app">
    <!-- 页面中有多个一样结构的标签: span+button -->
        <span>{
   
   {count1}}</span> <button @click="changeCount1">按钮</button> <br>
        <span>{
   
   {count2}}</span> <button @click="changeCount2">按钮</button> <br>
        <span>{
   
   {count3}}</span> <button @click="changeCount3">按钮</button> <br>
        <span>{
   
   {count4}}</span> <button @click="changeCount4">按钮</button> <br>
        <span>{
   
   {count5}}</span> <button @click="changeCount5">按钮</button> <br>
</div>

<script src="./vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            count1: 0,
            count2: 0,
            count3: 0,
            count4: 0,
            count5: 0
        },
        methods: {
            changeCount1() {
                this.count1++;
            },
            changeCount2() {
                this.count2++;
            },
            changeCount3() {
                this.count3++;
            },
            changeCount4() {
                this.count4++;
            },
            changeCount5() {
                this.count5++;
            }
        }
    });
</script>

question:

  1. code duplication

  2. not conducive to maintenance

Solution: Use a very important feature in Vue - components

<div id="app">
    <!-- 2. 使用组件 -->
    <span-btn></span-btn>
    <span-btn></span-btn>
    <span-btn></span-btn>
    <span-btn></span-btn>
</div>

<script src="./vue.js"></script>
<script>
    // 注册全局组件
    Vue.component('span-btn', {
        template: `
			<div>
				<span>{
   
   {count}}</span> 
				<button @click="changeCount">按钮</button>
                <br>
    		</div>
		`,
        data() {
            return {
                count: 0
            }
        },
        methods: {
            changeCount() {
                this.count++;
            }
        }
    });

    new Vue({
        el: '#app'
    });
</script>

What is a component:

The component system is another important concept of Vue, allowing us to build large applications using small, independent and often reusable components.

Think about it, almost any type of application interface can be abstracted into a component tree:

For example, you might have components such as header, sidebar, content area, etc., each of which contains other components like navigation links, blog posts, etc.

  • Components are reusable Vue instances with a name

  • Component options:

    • Components receive the same options as new Vue: eg  data, computed, watch, methods and lifecycle hooks, etc.

    • The only exceptions are root  el -instance-specific options like this

  • In addition, components also have their own options template, components, etc.

Component Features

  • A component is a package

  • Components allow us to reuse existing html, css, js

  • reusable

  • is a special Vue instance

  • Can be reused any number of times

  • Every time a component is used, a new instance of it is created

  • The data requirement in the component must be a function and needs to return an object

    • Components have their own scope

  • template Each component template has one and only one root element

Suggestion: In actual development, use various third-party components such as element-ui/mint-ui/iview as much as possible

Classification and use of components

  • Classification: Global Registration and Local Registration

  • Use (steps): 1. Register component 2. Use component by component name

global registration

  1. Use Vue.component (component name, component options) to register

    Component name: Recommended naming method of lowercase plus and minus signs

  2. new VueUsed by any (via ) newly created (one or more) Vue instances after it has been registered 

Vue.component('组件名', {
    // 组件选项: data methods template等(没有el)
    // data 的值是一个函数, 需要返回一个对象
});
<div id="app">
    <!-- 2. 使用组件 -->
    <span-btn></span-btn>
    <span-btn></span-btn>
    <span-btn></span-btn>
    <span-btn></span-btn>
</div>
<hr>
<div id="app1">
    <span-btn></span-btn>
    <My-Component></My-Component>
</div>
<hr>
<div id="app2">
    <span-btn></span-btn>
</div>
<hr>
<div id="app3">
    <span-btn></span-btn>
</div>

<script src="./vue.js"></script>
<script>
    // 1. 注册组件
    // Vue.component('组件名', {
    //     // 组件选项: data methods template等
    // });

    Vue.component('span-btn', {
        // template: 页面字符串,有且仅有一个根元素
        template: `
			<div>
				<span>{
   
   {count}}</span> 
				<button @click="changeCount">按钮</button>
                <br>
    		</div>
		`,
        data() {
            return {
                count: 0
            }
        },
        methods: {
            changeCount() {
                this.count++;
            }
        }
    });

    Vue.component('myComponent', {
        template: `
			<div>
				<h1>{
   
   {num}}</h1> 
				<button @click="changeTitle">按钮</button>
                <br>
    		</div>
		`,
        style: './style.css',
        data() {
            return {
                num: 0
            }
        },
        methods: {
            changeTitle() {
                this.num++;
            }
        }
    });

    new Vue({
        el: '#app'
    });

    new Vue({
        el: '#app1'
    });
    new Vue({
        el: '#app2'
    });
    new Vue({
        el: '#app3'
    });
</script>

Notice:

  1. The global component must be written before the Vue instance is created to take effect under the root element

  2. Multiple different global components can be used in different Vue instances

  3. Each component has its own scope

partial registration

  • Register directly in the Vue instance through the components option

  • For  components each property in the object,

    • Its attribute name is the name of the custom element, and its attribute value is the option object of this component.

<body>
    <div id="app">
        <!-- 2 使用组件 -->
        <com-A></com-A>
        <com-B></com-B>
        <com-C></com-C>
    </div>
</body>

<script src="./vue.js"></script>
<script>
    // 局部组件的选项
    const comA = {
        template: `<div>{
   
   {titleA}}</div>`,
        data() {
            return {
                titleA: 'comA中的data里的titleA'
            }
        }
    };
    const comB = {
        template: `<div>{
   
   {titleB}}</div>`,
        data() {
            return {
                titleB: 'comB中的data里的titleB'
            }
        }
    };

    const comC = {
        template: `<div>{
   
   {titleC}}</div>`,
        data() {
            return {
                titleC: 'comC中的data里的titleC'
            }
        }
    };

    new Vue({
        el: '#app',
        // 1. 在Vue实例中设置components选项{组件名:组件选项}
        components: {
            // 在页面中的组件名:组件选项
            'comA': comA,
            'comB': comB,
            'comC': comC
        }
    });
</script>

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/119976656