Usecontext Vue3

Posted on  by admin
  • < script setup > is a new syntax sugar from Vue3.

The type is the suggestion in Vue's Git RFC. It should be made clear that this is not intended to completely replace any current writing.

Its purpose is to provide developers with more concise syntax and simplify the lengthy template code when using the Composition API to write its single file component.

Without using < script setup >, our code is:. When we need to import a component, we not only need to import it explicitly in the file header, but also need to add a declaration in the components field.

Moreover, if the variables declared in the setup need to be used by the template, they need to be returned explicitly at the end of the setup.

If your component template uses few variables, this situation can be reluctantly accepted.

However, when the variables and methods gradually increase, it is undoubtedly a boring thing to return after setup every time. You will also face great challenges when refactoring the code.

To solve this problem, vue3 added script setup syntax. After using < script setup >, the same function is realized. The code is as follows:. Not only the data, calculation attributes and methods, but also the instructions and components can be automatically obtained in our template, which is very magical.

To make a long story short, this syntax makes a single file component simpler.

  1. In the original words of the RFC, "the main goal of this proposal is to reduce the verbosity of the use of the Composition API within SFC by directly exposing the context of < script setup > to the template."

  2. This is what we just saw.

  3. We don't need to care about the value returned in the setup method (because sometimes we should forget to return the value we need in the setup, so the template can't get the corresponding value).

  4. We can simplify the code.

In script setup, component import is automatically registered:.

script setup

The component registration step is omitted, and there is no explicit action to export variables. Props needs to be defined by using defineProps. The usage is similar to that of props before.

Emit uses defineEmit to define events that a component can emit.

useContext accesses the slots and properties of the component. defineProps/defineEmit will make simple type inference based on the passed value.

Define props – as the name suggests, it allows us to define props for components;.

Define emits – defines the events that a component can emit.

useContext – the slots and properties of the component can be accessed.

Instructions are the same as components.

They are automatically registered when imported. The default value is true.

In this case, the attribute bindings of the parent scope that are not recognized as props will be "fallback" and applied to the root element of the child component as an ordinary HTML attribute.

If await is used, it needs to be used with suspend asynchronous component.

Final Thoughts

Volar is a vscode plug-in to enhance the vue writing experience. Using volar plug-in can get the best support for script setup syntax.

To learn more about script setup, click?? Added by e11rof on Wed, 09 Mar 2022 03:49:19 +0200. When working in the Vue 3 Composition API, there are brand new ways to access component functionality.

In this article, we’ll be taking a look at the setup function’s context argument.

These changes are necessary because, in the Composition API, we don’t have the same reference to this as we do in the Options API.

In the Options API, we could call console.log(this) in any of the options and get a reference to the component itself – giving us access to its props, computed properties, data, and more.

However, Vue 3 lets us use the Composition API, where all of our code is located inside a setup function.

Not the answer you're looking for? Browse other questions tagged vue.jsvuejs3vue-composition-api or ask your own question.

This means that setup is where we declare our reactive data, methods, and computed properties.

Setup runs before our component instance is actually created, and since our setup property is where we actually define basically everything for our component, there is no longer a reference to the component itself using this.

The Composition API gives us alternative ways to access important component information like its props and slots.

This is possible because our setup function takes two properties that let us access some component properties: props and context.

context is a Javascript object that exposes three component properties.

And these three properties are:. – the non-prop attributes passed to our component. context.slots – an object with all of our template slots’ render functions.

– the method for our component to emit events. Let’s take a deeper look at each of these.

Again, context.attrs contains all of the non-prop attributes passed to our component.

What does this mean? When we actually use our component, any element attribute we add that is not declared in our props will be available inside context.attrs.

context.slots

Say we have a custom component that accepts a prop called value. And then in a parent component, we pass it several attributes.

What don’t we have access to in setup

The result of our log statement will be:.

As you can see, it contains everything besides our declared props.

This includes things like event listeners and HTML attributes.

One important note here is attrs is not reactive.

Meaning that if we want to apply side effects in response to values of attrs changing, we should use the onUpdated lifecycle hook instead.

Next, context.slots is a little confusing, so let’s walk through an example of when it’s useful.

context.attrs

In short, context.slots gives us access to the render method of each of the slots.

This is useful when we’re writing our own custom render function, and not using template code.

Vue recommends using templates in a majority of use cases, but if you really want to use the full power of Javascript, we can create our own render functions.

The example in the Vue docs for a great time to use a custom render method is if we are creating a component that renders a slot value with different level heading depending on the value of a prop.

In this code, we’re using v-if and v-else-if conditionals for all 6 heading options.

So how do we access component properties?

And as you can see, there’s a lot of duplicate code, and it just looks extremely cluttered.

Instead, we could use the render function to programmatically generate our heading. With the Composition API setup function, that looks like this.

However, how do we get our slots to render?? That’s where context.slots comes into play.

By giving us access to every slot’s render function, we can easily add our slot to our render function.

Each slot is accessible by its name and since we did not explicitly name our slot, it’s named default.

Now, if we run this with a simple parent component like this.

Here’s what our finished DOM will look like. So, you likely won’t be using context.slots too often, but when you’re writing complex Javascript render functions, it’s a powerful feature.

And finally, context.emit replaces this.$emit as our way to emit events from our component.

This is useful for sending any sort of event, with or without data, to a parent component.

Let’s say we want to create an X button that emits an event called close.

Then inside our parent component, we can listen for this close event with the v-on directive.

context.emit

For a full guide on using emit in Vue, check out this article or YouTube tutorial!

So far we’ve seen how the Composition API gives us access to four different properties: props, attrs, slots, and emit.

But since setup runs before our component instance is created, we will not have access to these three component properties:.

These are properties that we declare inside setup itself, but we do not have a built-in way to access a list of all of the data properties, for example.

use

In this article, we’ve learned how the Composition API way of accessing some component properties.

参数类型含义
propsobject由父组件传递下来的数据
contextobject组件的执行上下文

Since we don’t have the same access to this as the Options API, the setup function has two arguments that we can use to access a component’s props, attrs, slots, and emit method.

By using the props and context arguments, we can access powerful component properties and add full functionality to all kinds of Vue projects.

If you have any questions, leave them in the replies below!

vscode supporting plug-ins

Modified5 months ago. I'm running into an issue with Vue 3 (alpha 4):.

Inside the setup() function I am trying to read the parent component. As per the documentation on https://vue-composition-api-rfc.netlify.com/api.html#setup it should expose the parent via the context argument, either as a property of context.attrs or directly as parent (see the SetupContext bit under 'typing').

inheritAttrs

I don't find the documentation to be very clear on whether parent should be accessed directly from SetupContext, or via SetupContext.attrs, so I've tried both ways, but to no avail.

Here's my issue, I can access the SetupContext and SetupContext.attrs (which is a Proxy) just fine when logging them.

SetupContext.attrs exposes the usual proxy properties ([[Handler]], [[Target]] and [[IsRevoked]]) and when inspecting [[Target]] it clearly shows the parent property.