How to build a Model Layer in Vue3 just like other MVC language? - model-view-controller

my name is DP, I have 2 years Vue2 experience, but I am new to Vue3. I am learning Vue3 recently, as I found the "setup(Composition API)" just like the "Controller(in MVC)" that I did in other language, so I am trying to build my test Vue3 project in MVC way, but I go some problem can anyone help? thx!
MVC Plan
M - use class
V - use <template> ... </template>
C - use setup
My Problem
working: using loadTopic_inSetup().then() in setup is working, because topicList_inSetup is defined in setup() too.
not working: using loadTopic_inModel() in setup is not working, I guess some kind data keep problem, because in console I can see the data already got from API
as u can see, I am not expert for js/ts, I am a backend developer, so if you know how to do it, plz help thx very much.
BTW, VUE is greet, I love it.
My Code
//APIBased.ts
import { ajax } from "#/lib/eeAxios"
export class APIBased {
//load data with given url and params
loadData(apiPath: string, params?: object): Promise<any> {
apiPath = '/v1/'+apiPath
return ajax.get(apiPath, params)
}
}
//Topic.ts
import { APIBased } from "./APIBased";
import { ref } from 'vue'
export class Topic extends APIBased {
//try keep data in model
topicList: any = ref([]);
constructor() {
super()
}
//direct return ajax.get, let setup do the then+catch
loadTopic_inSetup() {
return super.loadData('topics', { t_type_id: 1 })
}
//run ajax get set return data to this.topicList, keep data in model
loadTopic_inModel() {
super.loadData('topics', { t_type_id: 1 }).then((re) => {
console.log(re.data)
this.topicList = re.data
})
}
}
//EETest.vue
<template>
<EELayoutMainLayout>
<template v-slot:mainContent>
<h1>{{ "Hello Vue3 !!" }}</h1>
<hr/>
{{to.topicList}} //not working... just empty array
<hr/>
{{topicList_inSetup}} //working... topic list return from API show here.
</template>
</EELayoutMainLayout>
</template>
<script lang="ts">
import { defineComponent, getCurrentInstance, ref } from 'vue'
import EELayoutMainLayout from '#/components/eeLayout/EELayoutMainLayout.vue'
import { Topic } from "#/models/Topic";
export default defineComponent({
name: 'EETest',
props: {
},
setup() {
let topicList_inSetup = ref([])
const to = new Topic()
//try keep data in setup, it's working
to.loadTopic_inSetup().then((re) => {
topicList_inSetup.value = re.data
console.log(re.data)
})
//try keep data in model, the function is run, api return get, but data not show, even add ref in model
to.loadTopic_inModel()
return {
topicList,
to,
}
},
components: {
EELayoutMainLayout,
},
})
</script>

A few digressions before solving the problem. Maybe you are a java developer. I personally think it is inappropriate to write the front end with Java ideas. The design of vue3's setup is more inclined to combined functional programming
To fully understand why you need some pre knowledge, Proxy and the get and set method of Object
They correspond to the two core apis in vue, reactive and ref,
The former can only be applied to objects( because proxy can only proxy objects),The latter can be applied to any type(primary for basic javascript types, get and set can apply for any type)
You can modify the code to meet your expectations
loadTopic_inModel() {
super.loadData('topics', { t_type_id: 1 }).then((re) => {
console.log(re.data)
this.topicList.value = re.data
})
}
You cannot modify a ref object directly, a test case to explain what is reactive
when ref function is called, a will be like be wrapped in a class has value properties, and has get and set method
the effect function will call the arrow function, and in this time, the get method of a will be called and it will track as a dependence of the effect function, when a changed, the set method of a will be called, and it will trigger the arrow function,
so when you direct modify the a, the setter method will never trigger, the view will not update
const a = ref(1)
let dummy
let calls = 0
effect(() => {
calls++
dummy = a.value
})
expect(calls).toBe(1)
expect(dummy).toBe(1)
a.value = 2
expect(calls).toBe(2)
expect(dummy).toBe(2)
// same value should not trigger
a.value = 2
expect(calls).toBe(2)

Related

How to create a computed based on another computed from composable

I'm learning composition API doing a simple todo app but then with multiple swim-lanes (todo, doing, done).
in useTasks.js composable I create "global" sourceTasks reactive, that later gets filled with data pulled from an API. Then it is reduced in tasks computed property, like this:
// useTasks.js
const sourceTasks = reactive({
list: []
});
export default function useTasks() {
const tasks = computed(() => {
return sourceTasks.list.reduce(divideIntoSwimLanes, [])
});
...
return {
tasks,
loadTasks,
createTask
}
}
Nothing too complicated.
Then I've got this SwimLane component, that well... uses the tasks :)
// SwimLane.vue - setup
async setup(props) {
const { status } = toRefs(props);
const { tasks, createTask } = useTasks();
return {
tasks,
label,
createTask
}
}
// SwimLane.vue - template
<single-task class="m-3" v-for="task in tasks[status]" :title="task.title" :id="task.id"/>
This works, but I don't find it elegant. I would prefer to create a new computed inside of SwimLane's setup, that holds the value of tasks for the given SwimLane. Putting it in the template obscures the logic.
I would expect this to work, but it does not, I think it loses the reactivity but I cant wrap my head around why:
// SwimLane.vue - alternative setup
const currentContextTasks = computed(() => {
return tasks.value[status]
});
return {
currentContextTasks
}
The problem feels a bit ridiculous, but my main concern is that I have misunderstood some core concept, hence this lengthy post.
This is like a biggest blunders ever. So right, the post was really helpful as a form of talking to the rubber duck.
What I did forgot to do is use the value of the status. Since it is a ref, I had to use it as follows:
const currentContextTasks = computed(() => {
return tasks.value[status.value] // 'status.value' and not just 'status'
});

Multiple Queries/Mutation in Apollo 2.1

I need some help using the new Query and Mutation component in Apollo 2.1, especially with multiple queries and mutations.
I have the following problems:
I have a graphql request that depends on a previous graphql result, how can I deal with this?
How do I add two different mutations (in my component I need to do two different actions) in a component that already has a query?
edit 2019/08/24
from the Apollo docs:
The new hooks API for Apollo Client is a simpler way to fetch data in
your React app without the boilerplate of render prop components and
higher-order components (HOC). We recommend using hooks for all new
Apollo code going forward.
original answer:
You are supposed to nest them. See this example:
const NumbersWithData = () => (
<Query query={QueryOne}>
{({ loading: loadingOne, data: { one } }) => (
<Query query={QueryTwo}>
{({ loading: loadingTwo, data: { two }}) => {
if (loadingOne || loadingTwo) return <span>loading...</span>
return <h3>{one} is less than {two}</h3>
}}
</Query>
)}
</Query>
);
To help with keeping the nesting manageable, you could check react-adopt. They have an Apollo ToDo App example, where they combine a Query and multiple Mutations.
For this purpose react-apollo exports a compose function. Using this function you may cleanly use several component enhancers at once. Including multiple graphql(), or even Redux connect() enhancers.
import { Mutation, compose, graphql } from "react-apollo";
class AddTweet extends Component {
....
....
....
}
export default compose(
graphql(GET_AUTHORS, { name: "getAuthors" }),
graphql(ADD_TWEET, { name: "addTweet" }),
connect(...), // incase you are using Redux
)(AddTweet);
An important note is that compose() executes the last enhancer first and works its way backwards through the list of enhancers.
One more thing lets say you were using this.props.data now you will get get undefined. just console.log(this.props) and you will see what is happening to props now. You will be having two properties now getAuthors and addTweet. So now it will be this.props.name-in-compose.name-of-type-in-typeDefs i.e. this.props.getAuthors.getUsers. It took me a bit to figure it out.
In my opinion,
To make a request depends on previous request, you can break that request to children component and pass result of previous request like props to it and do that request.
To use more than one mutation and queries, you can use compose like this
...
#compose(
graphql(GET_FEEDS_QUERY, {name : 'getFeeds'}),
graphql(CREATE_NEW_POST, {name: "createNewPost"}),
graphql(LIKE_POST_MUTATION, { name: "unlikePostMutation"}),
...
)
class HomeScreen extends Component {
...
}
I wrote a Medium Post about how to combine Mutation and Query on the same Component.
Here is a snippet from the post
// other import
import {Query} from “Apollo-graphql”; // new Query Component
import gql from "graphql-tag";
import { graphql } from "react-apollo";
import UserComponent from '../component/UserComponent'; // any component to display query result
const GET_ALL_USER = gql`
{
allUsers: {
firstname,
lastname,
username,
# other information
}
}
`
const UPDATE_USER_STATUS = gql`
mutation UpdateUserStatus($userID: ID!, $status: Int!){
updateUserState(userID: $userID, status: $status){
firstname,
lastname
username
# other information
}
}
`
ExampleComponent extends React.Component{
onEditInformation = async (user) => {
const response = await mutate({
variables: {userID: user}
})
}
render(){
return(
<Query query={GET_ALL_USER}>
{({data: { allUsers }}) => {
return allusers.map(user => {
return (
<UserComponent
user={user}
onEdit={() => this.onEditInformation(user)}
/>
)
})
}}
</Query>
)
}
}
export default graphql(UPDATE_USER_STATUS)(ExampleComponent);
Asides from using compose from react-apollo, another great utility library you can check it out is react-adopt. A great small utility lib that helps you to compose multiple render props type components so you don't have a nested hell patterns.
I have wrote a similar answer that basically covers all your current needs in terms of:
How to consume a previous result from your mapper fn via react-adopt
Combine multiple Query/Mutations from Composed component via react-adopt
Here's the detailed answer you're looking for & hopefully can be helpful to solving your problems :)
Best solution for this
Simply nest graphql function
export default graphql(addBookMutation)(graphql(getAuthorsQuery)(AddBook))
You can refer to this
Apollo concepts

Dynamic localization in vue-i18n

I would like to update my localization messages in vue-i18n dynamically.
I am building a webshop, where every item has descriptions in more languages. So what I’d like to achieve is when I get the webshop items from the REST API I want to put their names, descriptions etc. to the messages object in vue-i18n so it can work with them. Does the vue-i18n API have something to handle that? Also I am getting the data from the server (I get a Promise), so how can I make sure it gets updated in the browser view, when I finally get the response, and add the data to the localization?
What I did was write a mixin, and use it everywhere I need dynamic localization:
export default {
methods: {
$t: function (translate) {
if (typeof translate === 'string') {
return this.$i18n.t(translate)
} else if (translate === void 0) {
return this.$i18n.t('loading')
}
return translate[this.$i18n.locale]
}
}
}
This way when my texts look like the following, I can call $t(text) (NOT $t('text') of course):
data: function () {
return {text: {en:'Book', de:'Buch', hu:'Könyv'}}
}
So in your components you have to import this and add it as a mixin:
import dynamicLocalization from '#/components/mixins/dynamic-localization'
export default {
...
mixins:[dynamicLocalization]
...
}

React-native / Redux - error with state

So far I have been following various tutorials. This time I'm trying to build things from scratch (kind of). For now the following is supposed to display part of state. Later on I'll play with making it do calculations,etc. Still I get an error:
Cannot read property 'count' of undefined
So I use mapStateToProps and the first step I'd like to do is to get it to display this.props.count and this.props.step. Once I've done it I'll modify it to do more complex things.
Here's the component and below there's a link to the whole code that I put on github.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { getCounter } from '../actions';
class CounterBoard extends Component {
render() {
return (
<View>
<Text>BELOW SHOULD DISPLAY 0</Text>
<Text>{this.prop.count}</Text>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
count: state.count,
step: state.step
};
};
export default connect(mapStateToProps, { getCounter })(CounterBoard);
https://github.com/wastelandtime/calculator
Edit: Thank you for the 'prop' => 'props' pointer. Now I have the following error:
ExceptionsManager.js:63 Objects are not valid as a React child (found: object with keys {count, step}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Text`.
After going through your code on Github, I couldn't help but notice that in your action, you return the following object:
export const getCounter = (count) => {
return {
type: GET_COUNTER,
payload: count
};
};
If you intend to return the count, I assume that action.payload should contain a number here and not an object.
However, in your reducer, you return:
case GET_COUNTER:
return action.payload.count;
Assuming from the code in your CounterBoard Component and CalcReducer, you probably wanted to merge your payload into the initial state before returning from the reducer?
You might also need to pass and argument while dispatching the getCounter action, for the component to work as expected.

Vue.js: How to pass in data that isn't a parent / access vue methods?

I'm working on a simple timer app. I'm getting 3 pieces of data from the server: timers, projects and users. I believe I'm looping through timers correctly, but I'm not sure if I should be passing in data this way. I want different parts of my app to use the same dataset for users and projects in case a project name changes for example. Here's the code so far with questions embedded. I would like to do a single call for now for all the data at once.
<script>
Vue.component('sidebar-timer', {
props: ['timer','projects','users'],
computed: {
/***** SHOULD PROJECT AND USER BE SET A DIFFERENT WAY? *****/
project: function () {
return this.projects[this.timer.project_id.toString()];
},
user: function () {
return this.users[this.timer.user_id.toString()];
}
},
template: '<li class="project-item"><div class="timer-proj-name"> #{{ project.name }}</div><div class="timer-name"> #{{ user.name }}</div> <button class="timer-start-btn">Start</button><div class="timer-duration">#{{ timer.duration }}</div><div class="timer-status">#{{ timer.status }}</div><div id="toggle-timer-notes"><div class="timer-task"> #{{ timer.notes }}</div><div>timer id: #{{ timer.id }}<input :value="timer.id"></li></div>',
})
var TimerSidebar = Vue.extend({
methods: {
updateData: function () { // GET DATA FROM THE SERVER
var self = this;
$.get('/timers/getJson', function(response){
var userObj = response.users;
var projectObj = response.projects;
var timerObj = response.timers;
var timerArr = Object.keys(timerObj).map(function (key) {return timerObj[key]; });
/***** IS THERE A WAY TO SET projects AND users AT A LEVEL OUTSIDE OF TimerSidebar? *****/
self.$set(self, 'users', userObj);
self.$set(self, 'projects', projectObj);
self.$set(self, 'timers', timerArr);
})
}
}
})
var timerSidebar = new TimerSidebar({
el: '#timer-sidebar',
data: {
timers: [],
projects: [],
users: []
},
})
methods: {
/***** HOW TO ONCLICK CALL updateTimers FROM OUTSIDE THE COMPONENT? *****/
updateTimers: function(){ // ADD TIME RECORD FROM CLICK EVENT
var newTimers = this.timers;
newTimers.push({id: 166, project_id: 123, user_id: 1});
newTimers.sort(function(timer1, timer2){
if(timer1.id > timer2.id){
return 1;
} else if(timer1.id < timer2.id){
return -1;
} else {
return 0;
}
});
this.timers = newTimers;
}
}
This is the standard case when you should be going for a centralised state management. As you have data which is going to be used by multiple components, If the data flow is just limited to one way: parent to child, it can be manageable, but as soon as you get the requirement of updating the parent data when child changes it, or worse, updating the sibling data when another sibling changes it, it becomes messy.
Vue provides it own Flux like implementation, but the general practice is to go with vuex. With this, you store all your projects/users etc in vuex state, and each component can read/update from the central state. If its changed by one component, updated version is available to all components reactively. You can initiate the data in one place using actions in vuex itself.
Following is the architecture diagram:
You can have a look at my answer here on similar question and have a look at example on how to call api and save data in store.

Resources