vue程序访问本地api
While I have a love for Vue.js 2, there are some limitations on how reusable components are and how the code has to be laid out. This has been both a blessing a curse. On the one hand, for simple components, it makes learning Vue super easy and a low barrier to entry. On the other hand, as components get more complicated, you find that code for different features in the same component is munged (is that a word?).
虽然我很喜欢Vue.js 2,但是在可重用组件的方式以及代码的布局方面存在一些限制。 这一直是福的诅咒。 一方面,对于简单的组件,这使学习Vue非常容易,入门门槛也很低。 另一方面,随着组件变得越来越复杂,您会发现同一组件中用于不同功能的代码变得杂乱无章(这是一个单词吗?)。
Vuejs 3 has overcome this limitation with the composition API
. in this article, I will demonstrate these limitations in Vuejs 2 and show you the optional new approach for using the composition API.
Vuejs 3通过composition API
克服了这一限制。 在本文中,我将在Vuejs 2中演示这些限制,并向您展示使用成分API的可选新方法。
As hinted at above, you are not forced to use the composition API it’s optional. For smaller components, just keep doing things the way you always did. As your components get more complex, perhaps having more than one feature, the composition API is really useful.
正如上面所暗示的那样,您不必强制使用composition API,它是可选的。 对于较小的组件,只需保持与往常一样的方式工作即可。 随着您的组件变得越来越复杂(也许具有多个功能),composition API确实很有用。
GitHub上的所有代码 (All the code on GitHub)
I have developed a simple blog application, with two branches. One branch uses the Vue 2 options API and the other the Vue 3 Composition API
我开发了一个简单的博客应用程序,有两个分支。 一个分支使用Vue 2选项API,另一分支使用Vue 3 Composition API
https://github.com/simonjcarr/vue3_composition_api
https://github.com/simonjcarr/vue3_composition_api
学习曲线 (Learning curve)
There is a learning curve to the composition API, but it’s worth it. To give you an idea of why it’s so useful, I am going to give you a peek of what we will create in this article. I am hoping you will see it’s worth persevering for the benefits it brings.
合成API有一个学习曲线,但这是值得的。 为了让您了解它为何如此有用,我将向您介绍我们将在本文中创建的内容。 我希望您会发现它所带来的好处值得坚持不懈。
Here are two pieces of code, both are from the same component. The first use the Vue 2 Options API that you will be familiar with, the second uses the new Composition API
这是两段代码,都来自同一组件。 第一个使用您将熟悉的Vue 2 Options API,第二个使用新的Composition API
Without the composition API
没有合成API
The same component with the composition API
与成分API相同的组件
Not only does the composition API make the code much simpler, but as you will see through this article the code that is being imported from @/composables/blog/posts
is reusable in other components.
Composition API不仅使代码更简单,而且正如您将在本文中看到的那样,从@/composables/blog/posts
导入的代码可在其他组件中重用。
更新Vue CLI (Update the Vue CLI)
Before we create a new application, make sure you have the latest Vue CLI
在创建新应用程序之前,请确保您具有最新的Vue CLI
npm install -g @vue/cli
创建一个新的应用程序 (Create a new app)
vue create vue3_composition_api
When prompted, select Manually select features
, then use the space bar to toggle features on and off until you have the same selection as I have done below.
出现提示时,选择Manually select features
,然后使用空格键打开和关闭要素,直到您具有与下面相同的选择。
When done press enter
完成后,按Enter
Make sure to select Vue version 3.x (Preview)
and press enter
确保选择Vue版本3.x (Preview)
,然后按Enter
Other settings should be as follows
其他设置应如下
Use history mode for router?
Yes
对路由器使用历史记录模式?
Yes
Choose the linting version you prefer, I use
ESLint + Prettier
选择您喜欢的
ESLint + Prettier
版本,我使用ESLint + Prettier
- Lint on save 保存时不掉毛
- In Dedicated config files 在专用配置文件中
Save this as a preset for future projects?
No
将此保存为预设以供将来的项目使用吗?
No
After the installation is complete move into the application folder with
安装完成后,使用以下命令移至应用程序文件夹
cd vue3_composition_api
添加顺风CSS (Add tailwind CSS)
In my code, I have used tailwind CSS. It is super easy to install with Vue.
在我的代码中,我使用了顺风顺水CSS。 使用Vue超级容易安装。
vue add tailwind
When prompted select minimal
出现提示时,选择minimal
启动应用 (Start the app)
In the terminal at the root of your app
在应用程序根目录的终端中
npm run serve
Vue will start and tell you which port your app is running on, for me it is 8080
Vue将启动并告诉您您的应用程序正在哪个端口上运行,对我来说是8080
Open a browswer and navigate to http://localhost:8080
打开浏览器并浏览至http://localhost:8080
You might notice some formating issues, that is not a problem it due to tailwind conflicting with some of the boilerplate CSS generated by the basic Vue app.
您可能会注意到一些格式问题,这不是问题,因为顺风与基本Vue应用程序生成的一些样板CSS冲突。
删除样板代码 (Removing the boilerplate code)
We will start by removing some boilerplate files and code generated by Vue.
我们将首先删除一些Vue生成的样板文件和代码。
Delete HelloWorld.vue
from /src/components/HelloWorld.vue
Delete About.vue
from /src/views/About.vue
删除HelloWorld.vue
从/src/components/HelloWorld.vue
删除About.vue
从/src/views/About.vue
Edit /src/App.vue
so it contains the following code.
编辑/src/App.vue
,使其包含以下代码。
Edit /src/views/Home.vue
so it contains the code below.
编辑/src/views/Home.vue
,使其包含以下代码。
Edit /src/router/index.js
to contain the following code
编辑/src/router/index.js
以包含以下代码
Following those edits, you should have no errors in your app, but your browser should be a blank, white canvas.
完成这些编辑后,您的应用程序应该没有错误,但是浏览器应该是一块空白的白色画布。
添加标题 (Add a header)
Create a new file in /src/components/site/header/Header.vue
(You will have to create the folders site/header
)
在/src/components/site/header/Header.vue
创建一个新文件(您将必须创建文件夹site/header
)
In Header.vue
add the following code.
在Header.vue
添加以下代码。
Now lets tell Vue to use the Header component and display it.
现在,让Vue使用Header组件并显示它。
Edit /src/App.vue
so the file contains the following code.
编辑/src/App.vue
以便该文件包含以下代码。
In the above code, I have imported the component Header.vue
and added it to the components option.
在上面的代码中,我已导入组件Header.vue
并将其添加到components选项。
I have added some HTML structure to the template along with some tailwind CSS classes, and of course, added the
component.
我已经向模板添加了一些HTML结构以及一些顺风顺水CSS类,当然,还添加了
组件。
Also, note that I have added :key="$route.fullPath"
to the
element This fixes some reactivity problems where Vue would not know the route had changed if the only thing to change in the URL is a parameter. We will be using URL parameters to view individual blog articles.
另外,请注意,我已经在
元素中添加了:key="$route.fullPath"
,这解决了一些React性问题,如果URL中唯一要更改的是参数,Vue将不知道路由已更改。 我们将使用URL参数来查看各个博客文章。
If you check your browser, you should now have a header and a central section for the main site content.
如果您检查浏览器,现在应该有一个标题和一个主要部分,用于显示主要站点内容。
博客文章组件 (Blog post Components)
The last 3 components I will create are shown below. I will go over the content once we have created all the files and App is ready to use.
我将创建的最后3个组件如下所示。 一旦我们创建了所有文件并且App可以使用了,我将检查内容。
/src/components/blog/BlogRoll.vue
/src/components/blog/LatestPosts.vue
/src/components/blog/Post.vue
The code for each of them is below. Again these are just the normal Vue components based on the Options API.
每个代码如下。 同样,这些只是基于Options API的普通Vue组件。
/src/components/blog/BlogRoll.vue
/src/components/blog/BlogRoll.vue
/src/components/blog/LatestPosts.vue
/src/components/blog/LatestPosts.vue
/src/components/blog/Post.vue
/src/components/blog/Post.vue
使一切正常 (Getting everything working)
Now lets wire up these components into the app
现在,将这些组件连接到应用程序中
Edit the file /src/views/Home.vue
with the following code.
使用以下代码编辑文件/src/views/Home.vue
。
In the above file, I have imported the BlogRoll component and rendered it in the template
在以上文件中,我已导入BlogRoll组件并将其呈现在模板中
Edit /src/App.vue
so it contains the following code.
编辑/src/App.vue
,使其包含以下代码。
Finally, I will add a new route that will allow individual blog posts to be viewed. Edit /src/router/index.js
and update it to contain the code shown below.
最后,我将添加一条新路径,该路径将允许查看各个博客文章。 编辑/src/router/index.js
并将其更新为包含以下代码。
If you now check your browser, everything should be working.
如果现在检查您的浏览器,则一切正常。
We have a Blog Roll in the main content of the page if you click a post title, it takes you to that post.
如果您单击帖子标题,则页面的主要内容中将包含一个Blog Roll,它将带您到该帖子。
The LatestPosts component is rendered on the right of the page, and shows, just the last 10 posts. Again click one of those items, allows you to view the full post.
LatestPosts组件呈现在页面的右侧,并仅显示最后10个帖子。 再次单击这些项目之一,即可查看完整的帖子。
到目前为止的总结 (Summary so far)
The app is working. It’s very simple, you can’t create new posts, instead, all posts are pulled from the https://jsonplaceholder.typicode.com/
该应用程序正在运行。 这很简单,您无法创建新帖子,相反,所有帖子均从https://jsonplaceholder.typicode.com/提取
The key thing to note is that each of the 3 blog components, is each pulling content from the jsonplaceholder. In the case of BlogRoll and LatestPosts, they both pull the same content. It would be better to do this from a single place.
需要注意的关键是3个博客组件中的每个组件都是从jsonplaceholder中提取内容。 对于BlogRoll和LatestPosts,它们都提取相同的内容。 最好从一个地方进行此操作。
I know this is a contrived example, and for this particular app, you would be better using Vuex, but it works to demonstrate the principle, while still being relatively simple so you can understand the concept.
我知道这是一个虚构的示例,对于这个特定的应用程序,使用Vuex会更好,但是它可以演示原理,同时仍然相对简单,因此您可以理解该概念。
更新应用程序以使用Composition API (Updating the App to use the Composition API)
At a high-level, the process of using the Composition API is as follows
在高层次上,使用Composition API的过程如下
- Create a javascript file, referred to as a composable, which exports the data and methods you want your components to have access to. 创建一个称为composable的javascript文件,该文件将导出您希望组件可以访问的数据和方法。
- Import the composable into a component and add a setup() method, in which you can import the data and methods exported by the composable. 将composable导入组件并添加setup()方法,在其中可以导入由composable导出的数据和方法。
Lets first convert one of the components to use the composition API and then talk about what we have done.
让我们首先转换一个组件以使用composition API,然后再谈谈我们所做的事情。
创建可组合文件。 (Create the composable file.)
create a new file /src/composables/blog/posts.js
and add the code shown below.
创建一个新文件/src/composables/blog/posts.js
并添加以下代码。
Let’s take a bit of time to talk about some key points.
让我们花一些时间来谈论一些关键点。
参考 (ref)
ref is used to make variables in the composition API reactive. After import ref
from Vue, you will see I have declared 3 variables using ref()
ref用于使成分API中的变量具有React性。 从Vue导入ref
后,您将看到我已经使用ref()
声明了3个变量
let post = ref({});
let posts = ref([]);
let user = ref({});
By making a variable reactive, ref converts it to an object. You no longer access it’s value directly, instead you use .value
for example the posts array
could be accessed through posts.value[0]
or you could push an element into its array with posts.value.push({title: 'Hello World'})
通过使变量具有React性,ref将其转换为对象。 您不再直接访问它的值,而是使用.value
例如可以通过posts.value[0]
访问posts array
,或者可以使用posts.value.push({title: 'Hello World'})
There are some other methods for utilising reactivity in the Vue composition API, you can read about them here https://v3.vuejs.org/guide/composition-api-introduction.html#standalone-computed-properties
在Vue composition API中还有其他利用React性的方法,您可以在这里阅读有关它们的信息https://v3.vuejs.org/guide/composition-api-introduction.html#standalone-computed-properties
一切都集中在一处 (Everything in one place)
The key takeaway is that everything that we need for all three of our components is now in this one file. We can put as much logic as we need in here, but we only expose what our components need. This is going to make the maintenance of our code much easier in the future.
关键要点是,我们所有这三个组件所需的所有内容现在都在此文件中。 我们可以在此处放置所需的逻辑,但是我们只展示组件所需的内容。 这将使我们将来的代码维护更加容易。
Next we will see how we can use this compostible file by refactoring the BlogRoll component.
接下来,我们将看到我们如何通过重构BlogRoll组件来使用可堆肥文件。
重构BlogRoll.vue (Refactor BlogRoll.vue)
Edit /src/components/blog/BlogRoll.vue
and update it as show in the code below.
编辑/src/components/blog/BlogRoll.vue
并进行更新,如下面的代码所示。
The template section has not changed.
模板部分未更改。
A new setup()
option has been added and the previous data,
methods
and mounted
options removed.
添加了新的setup()
选项data,
并删除了之前的data,
methods
和已mounted
选项。
A core concept to note about the setup()
option is that you can not use the this
keyword inside it, as setup(), is run before the rest of the component is available. You can however use this
to refer to variables inside setup from any other options in your component i.e. from within methods
or mounted
.
关于setup()
选项的一个核心概念是您不能在其中使用this
关键字,因为setup()在组件的其余部分可用之前就已运行。 但是,您可以使用this
从组件中的任何其他选项(即methods
内或mounted
内)引用setup内部的变量。
You will see that I am running onMounted
inside of setup, this has replaced the mounted
option when you are using the composition API. You can see that it also needs to be imported import { onMounted } from "vue";
您将看到我在安装onMounted
内部运行onMounted
,当您使用合成API时,它已替换了mounted
选项。 您会看到它也需要import { onMounted } from "vue";
导入import { onMounted } from "vue";
The first line of code inside the setup()
option imports the data and methods this component requires from the composable.
setup()
选项中的第一行代码从可组合项导入此组件所需的数据和方法。
const { posts, fetchPosts } = usePosts();
fetchPosts
is only used in the setup function when the component mounted.
fetchPosts
仅在安装组件时在设置功能中使用。
Finally, the only object required by the template
is made available to the component on the last line
最后, template
所需的唯一对象在最后一行对组件可用
return { posts }
Important Note: when refering to variables exported from the composable, you access their values through .value
. You don’t have to do this in string interpolation within the template, Vue does this for you. For example to use the value of posts
inside the setup() option, you would have to use posts.value
but in the template, you can simply refer to 'posts'
重要说明:当引用从可组合对象导出的变量时,可以通过.value
访问它们的值。 您不必在模板中的字符串插值中执行此操作,Vue会为您执行此操作。 例如,要在setup()选项中使用posts
的值,则必须使用posts.value
但是在模板中,您可以简单地引用'posts'
重构其余两个组件 (Refactoring the remaining two components)
Edit /src/components/blog/LatestPosts.vue
and add the following code
编辑/src/components/blog/LatestPosts.vue
并添加以下代码
Finally, edit /src/components/blog/Post.vue
and add the following code.
最后,编辑/src/components/blog/Post.vue
并添加以下代码。
With those last two components refactored, the app should still be working.
重构了最后两个组件后,该应用程序仍应可以正常工作。
Our components are now much simplier and all logic and async calls relating to blog posts is contained in one file. If we had a need to incorporate some other functionality into one of these components that was not directly related to a blog post, we could create another composable in exactly the same way and keep it’s logic seperate rather than mixing it into the same component.
现在,我们的组件更加简单,与博客文章相关的所有逻辑和异步调用都包含在一个文件中。 如果我们需要将某些其他功能集成到与博客文章没有直接关系的这些组件之一中,则可以完全相同的方式创建另一个可组合组件,并将其逻辑分开,而不是将其混合到同一组件中。
摘要 (Summary)
I have explained some of the benefits of the new Composition API, but you can read more and keep upto date with any updates on the offical Vue docs page for Vue 3 https://v3.vuejs.org/guide/introduction.html
我已经解释了新的Composition API的一些好处,但是您可以在Vue的官方Vue文档页面上阅读更多内容并保持最新, 网址为https://v3.vuejs.org/guide/introduction.html。
We have built an full app using the Vue 2 options API and converted it to use the Vue 3 composition API.
我们使用Vue 2选项API构建了一个完整的应用程序,并将其转换为使用Vue 3 composition API。
Remember all the code for this app is available on GitHub. The repo contains two branches, one with the app developed using the Options API
and another branch with the Composition API
https://github.com/simonjcarr/vue3_composition_api
请记住,此应用程序的所有代码均可在GitHub上找到。 回购包含两个分支,一个分支是使用Options API
开发的应用程序,另一个分支是带有Composition API
分支https://github.com/simonjcarr/vue3_composition_api
I hope you found this article helpful. Let me know if you liked it in the comments below.
希望本文对您有所帮助。 如果您喜欢以下评论,请告诉我。
翻译自: https://levelup.gitconnected.com/developing-a-full-app-using-the-vue-3-composition-api-4fd9431f2136
vue程序访问本地api