[Vue] options in Vue

Time:2021-10-21

Options in Vue

  1. data
  2. DOM
  3. Lifecycle hook
  4. resources
  5. combination
  6. other

1 data

  1. data
  2. props
  3. propsData
  4. methods
  5. watch

1.1 data

Of Vue instancesdata object

During initialization, Vue will recursively convert the property of data intogetter/setter, able to respond to data changes to_and$The property at the beginning will not be processed

The data in the component must return the name of an initial data objectfunction, if it is an object, multiple instances created by the component willShared referenceThis data object.

1.2 computed

Calculate attribute object
Properties in functional form: read only
Properties in the form of object: read and set through the set / get function

  data() {
    return {
      a: 1,
    };
  },
  computed: {
    fnA() {
      return this.a * 2;
    },
    oA: {
      get() {
        return this.a + 1;
      },
      set(newVal) {
        this.a = newVal * 2;
      },
    },
  },
  mounted() {
    console.log(this.fnA); //2
    console.log(this.oA); //2
    console.log(this.a); //1

    this.oA = 2;
    console.log(this.oA); //5
    console.log(this.a); //4
    console.log(this.fnA); //8
  },

1.3 methods

Method object
Mixed into Vue instances, these methods can be accessed directly through VM instances or used in instruction expressions. In methodthisAutomatically bind as Vue instance

1.4 watch

Set data detectionobject

  • Function and string form

     data() {
      return {
        a: 1,
        b: { c: "bar" },
      };
    },
    watch: {
      a: "show",
      b: "show",
    },
    methods: {
      show(val, oldVal) {
        console.log(val, oldVal);
      },
    },
    mounted() {
      this.a = 2; //2 1
      this.b.c = 2;
    },

    The function form is to replace the string with a function, which cannot be detected in depth

  • Object form

    data() {
      return {
        a: 1,
        b: { c: "bar" },
      };
    },
    watch: {
      a: {
        handler: "show",
        immediate: true,
      },
      b: {
        handler: "show",
        deep: true,
      },
    },
    methods: {
      show(val, oldVal) {
        console.log(val, oldVal);
      },
    },
    mounted() {
      this.b.c = 2;
    },
    // 1 undefined
    //observer observer

    handlerFollowed by a callback function,immediateIf it is true, it will be executed immediately,deepIf true, depth detection can be performed

  • Array form

    The array can be used in the form of string, function and object. When combined, they willCall in turn, multiple handlers can be set

1.5 props

Receive the data, array or object of the parent component

  • arrayIn simple form

    //Parent component
    <template>
    <div>
      <Child :name="{ obj, c }" />
    </div>
    </template>
    
    <script>
    import Child from "./components/Child.vue";
    export default {
    name: "App",
    data() {
      return {
        obj: {
          a: 1,
          b: 2,
        },
        c: 3,
      };
    },
    components: {
      Child,
    },
    };
    </script>
    //Subcomponents
    <template>
    <div>{{ name }}</div>
    </template>
    
    <script>
    export default {
    props: ["name"],
    };
    </script>

    After the parent component passes the data, the child component can receive it with an array

  • objectThe form can be used to modify the received datato configure

    //Parent component
    <Child :prop1="obj" :prop2="c" :prop3="d"/>
    //Subcomponents
    <template>
    <div>
      <span>{{ prop1 }}</span>
      <span>{{ prop2 }}</span>
      <span>{{ prop3 }}</span>
    </div>
    </template>
    
    <script>
    export default {
    props: {
      prop1: [Object, Array],
      prop2: Number,
      prop3: {
        type: Number,
        default: 0,
        required: false,
        validator(value) {
          return value >= 0;
        },
      },
    },
    };
    </script>

    Each attribute in props in the form of object can be detected, and type detection can be added to a single value or array

  • verification

    • type: type checkStringNumberBooleanArrayObjectDateFuctionSymbol, it also supports custom constructors, which can be checked by instanceof
    • default: no data receivedDefault value
    • requiredBoolean value, whether the prop must receive
    • validator: Judgmentfunction, pass the prop as a parameter to check

    A warning will be given when the conditions are not met

1.6 propsData

Only innewUsed in instances created

2 DOM

  1. el
  2. template
  3. render
  4. renderError

2.1 el

Only innewTakes effect when an instance is created
Provide a DOM element that already exists on the page as the mounting target of the Vue instance, which can be a CSS selector or an HtmlElement instance.

2.2 template

Onecharacter stringUsed as the identity of the Vue instance. The template willreplaceMounted elements. The contents of mounted elements will be ignored unless the contents of the template are distributedslot

If#Initially, it will be used as a selector and use the matching innerHTML as a template

When a render function is included in the option, the template is ignored

2.3 render

Rendering function, string templateAlternative scheme
Receive a createElement method as the first parameter to createVNode
If the component is a function component, the render function also receives an additionalcontextParameter to provide context information for function components without instances.

Exists in optionrenderFunction, the Vue constructor does nottemplateOptions or throughelExtract the HTML template from the mount element specified by the option and compile the rendering function

render(createElement){
    return createElement(
        'App',
        {
            style:{
                color:"red",
            },
        },
        [
            'text',
            CreateElement ('h1 ',' headline ')
        ]
    )
}

Createelemnt can receive three parameters. The first one is required and the last two are optional

  • Parameter 1: {string | object | function}
    It can be an HTML tag name, a component option object, or an async function that resolves any of the above
  • Parameter 2: {objcet}
    Data object corresponding to attribute in a template
  • Parameter 3: {Stirng | array}
    Child virtual node, bycreateElement()You can also use strings to generateText virtual node

2.4 renderError

renderError(h,err)
It only works in the developer environment. When the render function encounters an error, it provides another rendering output.
The error is passed to as the second parameterrenderError

3 resources

  1. directives
  2. filters
  3. components

3.1 directives

Hash table containing instructions available to Vue instances
Vue.directive

//Local registration
directives:{
    focus:{
        inserted(el,binding){
            el.focus();
            el.value = binding.value
        }
    }
}

3.2 filters

Hash table containing filters available for Vue instances
Vue.filter

//Local registration
filters:{
    upperCase(value){
        return value.toUpperCase()
    }
}

3.3 components

A hash table containing the components available to the Vue instance
Vue.component

//Local registration
import Child1 from './components/Child1.vue'
components:{
    Child1,
    Child2:{
        Template: "< H1 > the price of the shirt is {{price}} < / H1 >",
        data(){
            return {
                Price: "nine pounds and fifteen pence",
            }
        }
    }
}

4 combination

  1. parent
  2. mixins
  3. extends
  4. provide/inject

4.1 parent

Specify the parent instance of the created instance and establish a parent-child relationship
Sub instances can usethis.$parentAccess the parent instance,
The child instance is pushed into the parent instance$childrenIn array

let vm1 = new Vue({
    el: "#root1",
    data() {
        return {
            num: 1,
        }
    },
    async mounted() {
        await this.$nextTick()
        console.log('vm1', this.$children[0].num)
    },
})
let vm2 = new Vue({
    el: "#root2",
    data() {
        return {
            num: 2
        }
    },
    parent: vm1,
    mounted() {
        console.log('vm2', this.$parent.num)
    },
})
// vm2 1
// vm1 2

When using cli, locally registered components can directly use this. $parent and $children

4.2 mixins

Receive a mixed objectarray
Vue.mixin

//mixins.js
export const mixin1 = {
    created() {
        console.log(this._uid, "created")
    },
}
export const mixin2 = {
    mounted() {
        console.log(this._uid, "mounted")
    },
}
//Main.js global registration
import { mixin1 } from './mixins'
Vue.mixin(mixin1)
//Sub component local registration
import { mixin2 } from "../mixins";
export default {
  mixins: [mixin2],
};
// 0 'created'
// 1 'created'
// 2 'created'
// 2 'mounted'

The hooks of mixin are called in this order in the incoming order, and are called before calling the hook of the component itself
Can doOption merge, reusable instructions, components, methods, etc. can be incorporated into component options

4.3 extends

Extension component, which can be an option object or constructor
AndmixinSimilarly, mixin is equivalent to multiple inheritance, and extends is single inheritance

//extends.js
export const extend = {
    data() {
        return {
            a: "extend"
        }
    },
}
//Components
import { extend } from "../extends";
export default {
  extends: extend,
  data() {
    return {
      b: "my",
    };
  },
  mounted() {
    console.log(this.$data);
  },
};
//{a:'extentd',b:'my'}

4.4 provide/inject

Ancestral components to future generationsinjectionA dependency
Provide: Object / function return object
Inject: string array / object
The injected data isNon responsive, you can pass in a listener object to respond

  • Inject an object

    //Ancestor component
    provide: {
      bar: "foo",
    },
    //Descendant component
     Inject: [bar], // array receive
  • Injection function, return an object

    //Ancestor component
    provide(){
      return {
        bar:'foo'
      }
    }
    //Descendant component
    inject: {
      grand: {
        Default: "receive failed",
        from: "bar",
      },
    },

    When receiving keys with different names, you need to set from. Default can be a function to access the data of this component
    For a key with the same name, the default value is the same as the key

  • Data and props can use the injected value as the data entry

    inject: ["bar", "baz"],
    data() {
      return {
        a: this.bar,
      };
    },
    props: {
      b: {
        default() {
          return this.baz;
        },
      },
    },

5 others

  1. name
  2. delimiters
  3. functional
  4. model
  5. inheritAttrs
  6. comments

5.1 name

Component name
Semantic, easy to debug

5.2 delimiters

Custom text insert separator
Default:["{{","}}"]

Like vue.compile, it only takes effect in the full version

5.3 functional

Is itFunctional component

There is no management of any state, no quiver, any state passed to it, no life cycle method, and only some are receivedpropoffunction
That means it’s stateless, NoResponsive data, no instance (no)this(context)

The render function option can be added to functional components, and the second parameter context of render can provide context for components
See the official website for the fields included in the context
Functional component

5.4 model

Custom component in usev-modelTime customizationpropandevent
{prop:string,event:string}
defaultv-model:{prop:”value”,event:”input”}

//Custom components
Vue.component('my-input', {
    model: {
        prop: 'uname',
        event: 'change'
    },
    props: {
        uname: {
            type: String,
            default: 'Tom'
        },
        value:String
    },
    template: '<input type="text" :value="uname" @input="updateVal($event.target.value)">',
    methods: {
        updateVal(val) {
            this.$emit('change', val)
        }
    },
})
//Follow example
new Vue({
    data() {
        return {
            Uname: "Zhang San"
        }
    },
}).$mount("#root1")
//html
<div id="root1">
    < My checkbox V-model = "uname" value = "Li Si" > < / my checkbox >
</div>
  • The subcomponent receives the value of V-model through props and passes it to prop in the model option
  • When the data changes, the event change is triggered and a value is passed
  • The V-model of the parent component receives the outgoing value and realizes two-way transmission

v-model => props => model => :value @input => $emit => v-model

5.4 inheritAttrs

The Boolean value defaults to true
By default, attribute bindings of the parent scope that are not recognized as props will be “rolled back” and applied to the root element of the child component as ordinary HTML attributes

5.5 comments

The Boolean value defaults to false
Do you want to keep and render HTML comments in the template

Use in full version only