Moment For Technology

Compare and learn Vue and wechat applet

Posted on Nov. 29, 2022, 4:03 a.m. by Michael Stevens
Category: The front end Tag: The front end Wechat applets

First, life cycle

Post two pictures first:

Vue life cycle

Applets life cycle

In contrast, the hook functions of applets are much simpler.

When the vue hook function jumps to a new page, the hook function will be triggered, but the hook function of the small program, the page jumps in different ways, the trigger hook is different.

  • onLoad: page loading a page is only called once and can be done inonLoadGets the call to open the current pagequeryParameters.
  • onShow: Page display This function is invoked every time a page is opened.
  • onReady: A page is called only once after its initial rendering, indicating that the page is ready to interact with the view layer. The interface Settings are as followswx.setNavigationBarTitlepleaseonReadyThen set. See life cycle
  • onHide: Pages are hidden whennavigateToOr when the bottom TAB is switched.
  • onUnload: The page is uninstalled whenredirectToornavigateBackIs called when.
Data request

When a page loads data, the two hooks are used in a similar way. Vue requests data in created or Mounted, and applet requests data in onLoad or onShow.

Second, data binding

VUE: When VUE dynamically binds a variable to an attribute of an element, it precedes the variable with a colon:, for example:

img :src="imgSrc"/
Copy the code

Applet: When a variable is bound to an element attribute, it is surrounded by two curly braces. If not, it is considered a string. Ex. :

image src="{{imgSrc}}"/image
Copy the code

Third, list rendering

Paste code directly, the two are still somewhat similar:

ul id="example-1"
  li v-for="item in items"
    {{ item.message }}
  /li
/ul

var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }
})
Copy the code

Small program:

Page({
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }
})

text wx:for="{{items}}"{{item}}/text
Copy the code

Show and hide elements

In VUE, use V-if and V-show to control the display and hiding of elements

In the applet, use wX-if and hidden to control the display and hiding of elements

5. Event handling

Vue: uses V-ON :event to bind events, or @event to bind events, for example:

button V-on :click="counter +=1"Add1/button button V-on :click.stop="counter+=1"Add1/buttonCopy the code

Bindtap (bind+event) catchtap(catch+event)

button catchtap="noWork" /button catchtap="noWork" /button catchtap="noWork" /button catchtap="noWork"Copy the code

6. Two-way data binding

1. Set the value

In VUE, you only need to add v-Model to the form element, and then bind a corresponding value in data. When the content of the form element changes, the corresponding value in data will change accordingly. This is a very nice point of VUE.

div id=" placeholder " input V-model ="reason" placeholder=" placeholder "class='reason'/ /div new Vue({el: '#app', data: { reason:'' } })Copy the code

But in applets, there is no such function. So what to do? When the content of the form changes, a method bound to the form element is triggered, in which the value on the form is assigned to the corresponding value in data via this.setData({key:value}). Here's the code to get a feel for it:

input bindinput="bindReason" placeholder=" placeholder "class='reason' value='{{reason}}' name="reason" / Page({data:{ reason:'' }, bindReason(e) { this.setData({ reason: e.detail.value }) } })Copy the code

When a page has a lot of form elements, changing values can be a physical task. Compared to a small program, vue's V-Model is awesome.

Value of 2.

In vue, the value can be this.reason

In the applet, use this.data.reason

7. Bind event parameters

In VUE, it is easy to bind event passing parameters. You just need to pass the data to be passed as parameters in the method that triggers the event, for example:

 button @ click = "say, 'I don't work tomorrow')"   / button  new Vue ({el: '# app, the methods: {say (arg) {consloe. Log (arg)}}})Copy the code

In the small program, you can not directly pass the parameter in the binding event method, you need to bind the parameter as the attribute value to the data- attribute on the element, and then in the method, through the e.currenttarget. Dataset.* way, so as to complete the parameter transfer, very difficult to have...

view class='tr' bindtap='toApprove' data-id="{{item.id}}"/view Page({ data:{ reason:'' }, toApprove(e) { let id = e.currentTarget.dataset.id; }})Copy the code

Parent and child component communication

1. Use of subcomponents

In VUE, you need:

  1. Writing child components
  2. Pass in the parent component you want to useimportThe introduction of
  3. invuethecomponentsRegistered in
  4. Used in templates
div @click="say" :title="title" class="icon-dismiss"/div /div /div /template script export default{ props:{ title:{ type:String, default:'' } } }, Methods :{say(){console.log(' not working tomorrow '); This.$emit('helloWorld')}} /script // Parent foo. Vue template div class="container" bar :title="title" @helloWorld="helloWorld"/bar /div /template script import Bar from './bar.vue' export default{ data(){ return{ Title :" I am the title "}}, methods:{helloWorld(){console.log(' I received the event from the child component ')}}, components:{Bar} /scriptCopy the code

In applets, you need:

  1. Writing child components

  2. In the JSON file of the child component, declare that file as a component

    {
      "component": true
    }
    Copy the code
  3. In the JSON file of the parent component to be imported, fill in the name and path of the imported component in usingComponents

    "usingComponents": {
        "tab-bar": ".. /.. /components/tabBar/tabBar"
      }
    Copy the code
  4. In the parent component, just import

    tab-bar currentpage="index"/tab-bar
    Copy the code

    Specific code:

    // Subcomponent ! --components/tabBar/tabBar.wxml-- view class='tabbar-wrapper' view class='left-bar {{currentpage==="index"?" Active ":""}}' bindtap='jumpToIndex' text class='iconfont icon-shouye'/text view /view /view view class='right-bar {{currentpage==="setting"?" Active ":""}}' bindtap='jumpToSetting' text class='iconfont icon-shezhi'/text view Setting /view /view /viewCopy the code

2. Communication between parent and child components

invueIn the

The parent component passes data to its child component by passing a value in the child component through v-bind. In the child component, the props receives the value. Example:

// Parent foo.vue template div class="container" bar :title="title"/bar /div /template script import bar from './bar.vue' export default{data(){return{title:" I am the title "}}, Components :{Bar} /script // subcomponent bar.vue template div class="search-box" div :title="title" /div /template script export default{ props:{ title:{ type:String, default:'' } } } /scriptCopy the code

The child component communicates with the parent component by passing methods and data to the parent component via this.$emit.

inSmall programIn the

Parent component to child component communication is similar to VUE, but instead of v-bind, the applet directly assigns a value to a variable, as follows:

tab-bar currentpage="index"/tab-barHere, "index" is the value to be passed to the child componentCopy the code

In the child component Properties, receive the passed value

properties: {
    // Popover title
    currentpage: {            / / the property name
      type: String,     // Type (mandatory), currently accepted types include: String, Number, Boolean, Object, Array, null (for any type)
      value: 'index'     // The initial value of the property (optional), if not specified one will be selected based on the type}}Copy the code

Child component communication to parent is similar to vUE, with the following code:

// In the child component
methods: {   
    // Pass to the parent component
    cancelBut: function (e) {
      var that = this;
      var myEventDetail = { pickerShow: false, type: 'cancel' } The detail object is provided to the event listener function
      this.triggerEvent('myevent', myEventDetail) //myevent Custom named event used in the parent component}},// In the parent component
bar bind:myevent="toggleToast"/bar

// Get child component information
toggleToast(e){
    console.log(e.detail)
}
Copy the code
If the parent component wants to call the child component's methods

Vue adds a ref attribute to the subcomponent, which can be retrieved from the value of this.$refs.ref, and can then call any method in the subcomponent, for example:

// Child bar ref="bar"/bar // parent this.$ref. Methods of child componentsCopy the code

An applet adds an ID or class to a child component, finds the child component via this.selectComponent, and calls its methods, as shown in this example:

// Child bar id="bar"/bar // Parent this.selectComponent('#id').syaHello()Copy the code
The applet parent changes the style of the child component

1. Parent passes style to child component 2. Parent passes variables to control child component style 3. In the parent component style, precede the child component class name with the parent class name

view class='share-button-container' bindtap='handleShareBtn'
   share-button  product="{{goodProduct}}" type="1" back-color="#fff" fore-color="#9e292f" bind:error="on_error" /
/view

.share-button-container .button--btn-navigator__hover{
  background: #fff;
}
Copy the code

Applets and Vue are too similar in this respect...

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.