# Component Templates and Styles

Like pages, custom components have their ownwxmltemplates andwxssstyles.

# Component Templates

Component templates are written in the same way as page templates. The node tree generated by the component template combined with the component data is inserted to the reference location of the component.

A 'node' can be provided in a component template to serve as a subnode provided when a component reference is made.

Code example:

Preview with Developer Tool

<!-- 组件模板 -->
<view class="wrapper">
  <view>这里是组件的内部节点</view>
  <slot></slot>
</view>
<!-- 引用组件的页面模板 -->
<view>
  <component-tag-name>
    <!-- 这部分内容将被放置在组件 <slot> 的位置上 -->
    <view>这里是插入到组件slot中的内容</view>
  </component-tag-name>
</view>

Note that the custom component referenced in the template and its corresponding node name need to be explicitly defined in thejsonfile, otherwise it will be considered a meaningless node.In addition, node names can be declared as abstract nodes .

# Template Data Binding

Similar to normal WXML templates, you can use data binding to pass dynamic data to properties of child components.

Code example:

Preview with Developer Tool

<!-- 引用组件的页面模板 -->
<view>
  <component-tag-name prop-a="{{dataFieldA}}" prop-b="{{dataFieldB}}">
    <!-- 这部分内容将被放置在组件 <slot> 的位置上 -->
    <view>这里是插入到组件slot中的内容</view>
  </component-tag-name>
</view>

In the above example, the components' propertiespropAandpropBreceive the data passed by the page.Pages can change the bound data fields bysetData.

Note: This data binding can only pass JSON-compatible data.Starting with the base library version {% version ('2.0.9')%}, you can also include functions in your data (but these functions cannot be called directly in WXML and can only be passed to child components).

# Slot of component wxml

In the component's wxml, you can include theslotnode, which hosts the wxml structure provided by the component user.

By default, there can be only one slot in a component's WXML. When you need to use multiple slots, you can declare enabled in component js.

Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: { /* ... */ },
  methods: { /* ... */ }
})

At this point, multiple slots can be used in the wxml of this component, distinguished by differentname.

<!-- 组件模板 -->
<view class="wrapper">
  <slot name="before"></slot>
  <view>这里是组件的内部细节</view>
  <slot name="after"></slot>
</view>

When used, theslotattribute is used to insert nodes into different slots.

<!-- 引用组件的页面模板 -->
<view>
  <component-tag-name>
    <!-- 这部分内容将被放置在组件 <slot name="before"> 的位置上 -->
    <view slot="before">这里是插入到组件slot name="before"中的内容</view>
    <!-- 这部分内容将被放置在组件 <slot name="after"> 的位置上 -->
    <view slot="after">这里是插入到组件slot name="after"中的内容</view>
  </component-tag-name>
</view>

# Component Style

The component corresponds to thewxssfile style, which is valid only for nodes within the component wxml.When writing component styles, you need to pay attention to the following:

  • Components and pages that reference components cannot use id selectors (# a), attribute selectors ([a]) and label name selectors, use class selectors instead.
  • Use descendant selectors in components and pages that reference components (.a.b)In some extreme cases, there will be unintended behavior, so avoid use if you do.
  • Child element selector (.a >.b)Can only be used between theviewcomponent and its child nodes, for other components that may cause unexpected situations.
  • Inherited styles, such asfont,color, are inherited from outside the component into the component.
  • With the exception of inherited styles, the styles inapagewxssand the styles on the page on which the component is located are not valid for custom components (unless you change the component style isolation option).
#a { } /* 在组件中不能使用 */
[a] { } /* 在组件中不能使用 */
button { } /* 在组件中不能使用 */
.a > .b { } /* 除非 .a 是 view 组件节点,否则不一定会生效 */

In addition, a component can specify the default style of its node, using the: hostselector (required to include a base library {% version ('1.7.2')%} or higher developer tool support).

Code example:

Preview with Developer Tool

/* 组件 custom-component.wxss */
:host {
  color: yellow;
}
<!-- 页面的 WXML -->
<custom-component>这段文本是黄色的</custom-component>

# Component style isolation

By default, custom component styles are only affected by custom component wxss. Unless there are two of the following:

  • Specifies a special style isolation optionstyleIsolation.
  • Under webview rendering, using a label name selector (or some other special selector) to specify a style directly inapagewxssor in thewxssof the page affects the page and all components.Usually this is not recommended practice.
{
  "styleIsolation": "isolated"
}

Preview with Developer Tool

ThestyleIsolationoption in custom component JSON is supported from the base library version {% version ('2.10.1')%}.It supports the following values:

  • Isolatedmeans that style isolation is enabled, and styles specified with class will not affect each other inside and outside the custom component (default in general);
  • Apply-sharedmeans that the page wxss style will affect the custom component, but the style specified in the custom component wxss will not affect the page;
  • Sharedindicates that the page wxss style will affect custom components,The style specified in the custom component wxss also affects pages and other custom components that haveapply-sharedorshared.(This option is not available in the plugin.))

When using the latter two, be sure to pay attention to how the patterns between components affect each other.

If this Component constructor is used to construct the page , the default value isshared,There are also several additional style isolation options available:

  • Page-isolatedmeans that apagewxss is disabled on this page, and the wxss of the page does not affect other custom components;
  • Page-apply-sharedmeans that apagewxss is disabled on this page. At the same time, the page wxss style does not affect other custom components, but custom components set tosharedaffect the page;
  • Page-sharedmeans that apagewxss is disabled on this page. At the same time, the page wxss style will affect other pages set toapply-sharedA custom component that isorsharedis also affected by a custom component that has been set toshares.

Other configuration methods no longer recommended

Starting with the Weixin Mini Program base library version {% version ('2.6.5')},styleIsolationcan be configured in theoptionsof the JS file.For example:

Component({
  options: {
    styleIsolation: 'isolated'
  }
})

In addition, Weixin Mini Program base library versions {% version ('2.2.3')%} above supportTheaddGlobalClassoption is set inComponent``options`` addGlobalClass: true。 This option is equivalent to settingstyleIsolation: apply-shared,This option will not work if thestyleIsolationoption is set.

Code example:

Preview with Developer Tool

/* 组件 custom-component.js */
Component({
  options: {
    addGlobalClass: true,
  }
})
<!-- 组件 custom-component.wxml -->
<text class="red-text">这段文本的颜色由 `app.wxss` 和页面 `wxss` 中的样式定义来决定</text>
/* app.wxss */
.red-text {
  color: red;
}

# External style classes

Start from base library version 1.9.90. Please remaining backward compatible.

Sometimes, a component wants to accept an externally incoming style class.You can then define several external style classes in theComponentwith theexternalClassesdefinition section.

This feature can be used to implement something similar to theviewcomponent'shover-classattribute: pages can provide a style class that givesview[[]] [[]]hover-class, the style class itself is written in the page rather than theviewcomponent implementation.

Note: When using common style classes and external style classes on the same node, the priorities of the two classes are undefined, so it's best to avoid this.

Code example:

/* 组件 custom-component.js */
Component({
  externalClasses: ['my-class']
})
<!-- 组件 custom-component.wxml -->
<custom-component class="my-class">这段文本的颜色由组件外的 class 决定</custom-component>

In this way, the user of the component can specify the class corresponding to the style class, just as with normal attributes.You can specify multiple corresponding classes after {% version ('2.7.1')%}.

Code example:

Preview with Developer Tool

<!-- 页面的 WXML -->
<custom-component my-class="red-text" />
<custom-component my-class="large-text" />
<!-- 以下写法需要基础库版本 2.7.1 以上 -->
<custom-component my-class="red-text large-text" />
.red-text {
  color: red;
}
.large-text {
  font-size: 1.5em;
}

# Refer to the style of a page or parent component

Start from base library version 2.9.2. Please remaining backward compatible.

Even with style isolationisolatedenabled, a component can still locally reference the style of the page on which the component resides or the style of the parent component.

For example, if you define in the page wxss:

.blue-text {
  color: blue;
}

In this component you can use~to reference the style of this class:

<view class="~blue-text"> 这段文本是蓝色的 </view>

If a component is defined in the parent component wxss:

.red-text {
  color: red;
}

In this component you can use^to reference the style of this class:

<view class="^red-text"> 这段文本是红色的 </view>

You can also use multiple^in succession to reference styles in an ancestor component.

Note: If a component is a more independent, generic component, prioritize the way you use external style classes rather than refer directly to the style of the parent component or page.

# Virtualized component nodes

Start from base library version 2.11.2. Please remaining backward compatible.

By default, that node of the custom component itself is a "normal" node on which you can set up when you use it.class``style, animation, flex layout, etc., just like a normal view component node.

<!-- 页面的 WXML -->
<view style="display: flex">
  <!-- 默认情况下,这是一个普通的节点 -->
  <custom-component style="color: blue; flex: 1">蓝色、满宽的</custom-component>
</view>

Sometimes, however, the custom component does not want the node itself to be able to set the style, respond to the flex layout, etc., but rather wants the first layer of the custom component to be responsive to the flexible layout or the style is entirely determined by the custom component itself.

In this case, you can set this custom component to be "virtual":

Component({
  options: {
    virtualHost: true
  },
  properties: {
    style: { // 定义 style 属性可以拿到 style 属性上设置的值
      type: String,
    }
  },
  externalClasses: ['class'], // 可以将 class 设为 externalClasses
})

This way, flex can be placed inside a custom component:

<!-- 页面的 WXML -->
<view style="display: flex">
  <!-- 如果设置了 virtualHost ,节点上的样式将失效 -->
  <custom-component style="color: blue">不是蓝色的</custom-component>
</view>
<!-- custom-component.wxml -->
<view style="flex: 1">
  满宽的
  <slot></slot>
</view>

Note that theclass``styleon the custom component nodeAnd the animation won't work again, but you can still:

  • Define style aspropertiesto get the value set on the style;
  • Defining a class as aexternalClassesexternalstyle class enables custom component wxml to use the class value.

Code example:

Preview with Developer Tool